refactor event handlers

This commit is contained in:
Thomas Amland 2021-04-18 20:41:38 +02:00
parent 86e66425d2
commit 56a30c484c
2 changed files with 40 additions and 42 deletions

View File

@ -3,9 +3,13 @@ export class AudioController {
private handle = -1
private volume = 1.0
private fadeDuration = 200
private eventHandlers = null as any
private buffer = new Audio()
ontimeupdate: (value: number) => void = () => { /* do nothing */ }
ondurationchange: (value: number) => void = () => { /* do nothing */ }
onended: () => void = () => { /* do nothing */ }
onerror: (err: MediaError | null) => void = () => { /* do nothing */ }
currentTime() {
return this.audio.currentTime
}
@ -14,10 +18,6 @@ export class AudioController {
return this.audio.duration
}
setEventHandlers(handlers: any) {
this.eventHandlers = handlers
}
setBuffer(url: string) {
this.buffer.src = url
}
@ -52,20 +52,20 @@ export class AudioController {
endPlayback(this.audio, this.fadeDuration)
}
this.audio = new Audio(url)
this.audio.ondurationchange = () => {
this.eventHandlers?.onDurationChange(this.audio.duration)
}
this.audio.onerror = () => {
this.eventHandlers?.onError(this.audio.error)
this.onerror(this.audio.error)
}
this.audio.onended = () => {
this.eventHandlers?.onEnded()
this.onended()
}
this.audio.ontimeupdate = () => {
this.eventHandlers?.onTimeUpdate(this.audio.currentTime)
this.ontimeupdate(this.audio.currentTime)
}
this.eventHandlers?.onDurationChange(this.audio.duration)
this.eventHandlers?.onTimeUpdate(this.audio.currentTime)
this.audio.ondurationchange = () => {
this.ondurationchange(this.audio.duration)
}
this.ondurationchange(this.audio.duration)
this.ontimeupdate(this.audio.currentTime)
this.audio.volume = 0.0
if (options.paused !== true) {

View File

@ -240,8 +240,7 @@ export const playerModule: Module<State, any> = {
}
export function setupAudio(store: Store<any>, api: API) {
audio.setEventHandlers({
onTimeUpdate: (value: number) => {
audio.ontimeupdate = (value: number) => {
store.commit('player/setCurrentTime', value)
// Scrobble
if (
@ -253,22 +252,21 @@ export function setupAudio(store: Store<any>, api: API) {
store.commit('player/setScrobbled')
api.scrobble(id)
}
},
onDurationChange: (value: number) => {
}
audio.ondurationchange = (value: number) => {
store.commit('player/setDuration', value)
},
onError: (error: any) => {
store.commit('player/setPaused')
store.commit('setError', error)
},
onEnded: () => {
}
audio.onended = () => {
if (store.getters['player/hasNext'] || store.state.player.repeat) {
return store.dispatch('player/next')
} else {
return store.dispatch('player/resetQueue')
}
},
})
}
audio.onerror = (error: any) => {
store.commit('player/setPaused')
store.commit('setError', error)
}
audio.setVolume(storedMuteState ? 0.0 : storedVolume)
const url = store.getters['player/track']?.url