Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
fix(h5): remove audio listeners when callback is omitted
  • Loading branch information
Jarvis636431 authored and Single-Dancer committed Nov 2, 2026
commit b9e0a469d3c0970f7848a63d71b9cd2481620fcc
166 changes: 166 additions & 0 deletions packages/taro-h5/__tests__/media/audio-listeners.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import Taro from '@tarojs/api'

import { createInnerAudioContext } from '../../src/api/media/audio'
import { InnerAudioContext } from '../../src/api/media/audio/InnerAudioContext'

const events = [
['Canplay', 'canplay'],
['Play', 'play'],
['Pause', 'pause'],
['Stop', 'stop'],
['Ended', 'ended'],
['TimeUpdate', 'timeupdate'],
['Error', 'error'],
['Waiting', 'waiting'],
['Seeking', 'seeking'],
['Seeked', 'seeked']
] as const

describe('InnerAudioContext listener removal', () => {
let contexts: InnerAudioContext[]

beforeEach(() => {
contexts = []
jest.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {})
})

afterEach(() => {
contexts.forEach(context => context.destroy())
jest.restoreAllMocks()
})

function create () {
const context = createInnerAudioContext() as InnerAudioContext
contexts.push(context)
return context
}

function emit (context: InnerAudioContext, event: string) {
if (event === 'stop') context.stop()
else context.Instance!.dispatchEvent(new Event(event))
}

describe.each(events)('off%s', (suffix, event) => {
test('without a callback removes all user listeners and allows subscribing again', () => {
const context = create()
const first = jest.fn()
const second = jest.fn()
context[`on${suffix}`](first)
context[`on${suffix}`](second)
context[`off${suffix}`]()
emit(context, event)
expect(first).not.toHaveBeenCalled()
expect(second).not.toHaveBeenCalled()

context[`on${suffix}`](second)
emit(context, event)
expect(first).not.toHaveBeenCalled()
expect(second).toHaveBeenCalledTimes(1)
})

test('explicit undefined and repeated removal also clear all listeners', () => {
const context = create()
const listener = jest.fn()
context[`off${suffix}`]()
context[`on${suffix}`](listener)
context[`off${suffix}`](undefined)
context[`off${suffix}`]()
emit(context, event)
expect(listener).not.toHaveBeenCalled()
})

test('a callback removes only that listener and an unknown callback removes none', () => {
const context = create()
const first = jest.fn()
const second = jest.fn()
context[`on${suffix}`](first)
context[`on${suffix}`](second)
context[`off${suffix}`](jest.fn())
emit(context, event)
expect(first).toHaveBeenCalledTimes(1)
expect(second).toHaveBeenCalledTimes(1)
context[`off${suffix}`](first)
emit(context, event)
expect(first).toHaveBeenCalledTimes(1)
expect(second).toHaveBeenCalledTimes(2)
})
})

test('offPlay preserves the internal first-play startTime handling', () => {
const context = create()
context.startTime = 12
const listener = jest.fn()
context.onPlay(listener)
context.offPlay()
emit(context, 'play')
expect(listener).not.toHaveBeenCalled()
expect(context.currentTime).toBe(12)
context.seek(3)
emit(context, 'play')
expect(context.currentTime).toBe(3)
})

test('removal is isolated by event and audio context', () => {
const first = create()
const second = create()
const play = jest.fn()
const pause = jest.fn()
const otherPlay = jest.fn()
first.onPlay(play)
first.onPause(pause)
second.onPlay(otherPlay)
first.offPlay()
emit(first, 'play')
emit(first, 'pause')
emit(second, 'play')
expect(play).not.toHaveBeenCalled()
expect(pause).toHaveBeenCalledTimes(1)
expect(otherPlay).toHaveBeenCalledTimes(1)
})

test('DOM callbacks retain their event, this and native duplicate-registration behavior', () => {
const context = create()
const audio = context.Instance!
const listener = jest.fn(function (this: HTMLAudioElement, event: Event) {
expect(this).toBe(audio)
expect(event.target).toBe(audio)
})
context.onPlay(listener)
context.onPlay(listener)
emit(context, 'play')
expect(listener).toHaveBeenCalledTimes(1)
context.offPlay(listener)
emit(context, 'play')
expect(listener).toHaveBeenCalledTimes(1)
})

test('offPlay during dispatch keeps native removal semantics for later listeners', () => {
const context = create()
const second = jest.fn()
context.onPlay(() => context.offPlay())
context.onPlay(second)
emit(context, 'play')
expect(second).not.toHaveBeenCalled()
})

test('destroy detaches listeners from the retained audio element and remains idempotent', () => {
const context = create()
const audio = context.Instance!
const play = jest.fn()
const error = jest.fn()
context.onPlay(play)
context.onError(error)
context.destroy()
audio.dispatchEvent(new Event('play'))
audio.dispatchEvent(new Event('error'))
Taro.eventCenter.trigger('__taroRouterChange')
expect(play).not.toHaveBeenCalled()
expect(error).not.toHaveBeenCalled()
expect(context.errorStack.count()).toBe(0)
expect(context.stopStack.count()).toBe(0)
expect(() => context.destroy()).not.toThrow()
for (const [suffix] of events) {
expect(() => context[`off${suffix}`]()).not.toThrow()
}
})
})
1 change: 1 addition & 0 deletions packages/taro-h5/__tests__/media/audio.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ describe('InnerAudioContext', () => {
test('removes the router listener and callbacks when destroyed', () => {
const audio = {
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
pause: jest.fn(),
removeAttribute: jest.fn(),
currentTime: 0,
Expand Down
76 changes: 52 additions & 24 deletions packages/taro-h5/src/api/media/audio/InnerAudioContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,14 @@ export class InnerAudioContext implements Taro.InnerAudioContext {
stopStack: CallbackManager
__startTime = 0
__isFirstPlay = true
private readonly listeners = new Map<string, Set<EventListener>>()
private readonly onRouterChange = () => this.stop()
private readonly onFirstPlay = () => {
if (this.__isFirstPlay) {
this.__isFirstPlay = false
this.seek(this.startTime)
}
}

constructor () {
this.Instance = new Audio()
Expand All @@ -18,12 +25,8 @@ export class InnerAudioContext implements Taro.InnerAudioContext {
this.Instance.onerror = this.errorStack.trigger

Taro.eventCenter.on('__taroRouterChange', this.onRouterChange)
this.onPlay(() => {
if (this.__isFirstPlay) {
this.__isFirstPlay = false
this.seek(this.startTime)
}
})
// Keep internal playback handling separate from removable user listeners.
this.Instance.addEventListener('play', this.onFirstPlay)
}

set autoplay (e) { this.setProperty('autoplay', e) }
Expand Down Expand Up @@ -65,6 +68,29 @@ export class InnerAudioContext implements Taro.InnerAudioContext {
}
}

private addListener (type: string, callback: EventListener) {
if (!this.Instance) return
let callbacks = this.listeners.get(type)
if (!callbacks) {
callbacks = new Set()
this.listeners.set(type, callbacks)
}
callbacks.add(callback)
this.Instance.addEventListener(type, callback)
}

private removeListener (type: string, callback?: EventListener) {
const callbacks = this.listeners.get(type)
if (callback) {
this.Instance?.removeEventListener(type, callback)
callbacks?.delete(callback)
} else {
callbacks?.forEach(listener => this.Instance?.removeEventListener(type, listener))
callbacks?.clear()
}
if (!callbacks?.size) this.listeners.delete(type)
}

play = () => this.Instance?.play()

pause = () => this.Instance?.pause()
Expand All @@ -86,31 +112,33 @@ export class InnerAudioContext implements Taro.InnerAudioContext {

this.stop()
Taro.eventCenter.off('__taroRouterChange', this.onRouterChange)
this.listeners.forEach((_, type) => this.removeListener(type))
this.Instance.removeEventListener('play', this.onFirstPlay)
this.Instance.onerror = null
this.Instance.removeAttribute('src')
this.errorStack.clear()
this.stopStack.clear()
this.Instance = undefined
}

onCanplay = (callback: Taro.InnerAudioContext.OnCanplayCallback = () => {}) => this.Instance?.addEventListener('canplay', callback as any)
onPlay = (callback: Taro.InnerAudioContext.OnPlayCallback = () => {}) => this.Instance?.addEventListener('play', callback as any)
onPause = (callback: Taro.InnerAudioContext.OnPauseCallback = () => {}) => this.Instance?.addEventListener('pause', callback as any)
onCanplay = (callback: Taro.InnerAudioContext.OnCanplayCallback = () => {}) => this.addListener('canplay', callback as any)
onPlay = (callback: Taro.InnerAudioContext.OnPlayCallback = () => {}) => this.addListener('play', callback as any)
onPause = (callback: Taro.InnerAudioContext.OnPauseCallback = () => {}) => this.addListener('pause', callback as any)
onStop = (callback: Taro.InnerAudioContext.OnStopCallback = () => {}) => this.stopStack.add(callback)
onEnded = (callback: Taro.InnerAudioContext.OnEndedCallback = () => {}) => this.Instance?.addEventListener('ended', callback as any)
onTimeUpdate = (callback: Taro.InnerAudioContext.OnTimeUpdateCallback = () => {}) => this.Instance?.addEventListener('timeupdate', callback as any)
onEnded = (callback: Taro.InnerAudioContext.OnEndedCallback = () => {}) => this.addListener('ended', callback as any)
onTimeUpdate = (callback: Taro.InnerAudioContext.OnTimeUpdateCallback = () => {}) => this.addListener('timeupdate', callback as any)
onError = (callback: Taro.InnerAudioContext.OnErrorCallback) => this.errorStack.add(callback)
onWaiting = (callback: Taro.InnerAudioContext.OnWaitingCallback = () => {}) => this.Instance?.addEventListener('waiting', callback as any)
onSeeking = (callback: Taro.InnerAudioContext.OnSeekingCallback = () => {}) => this.Instance?.addEventListener('seeking', callback as any)
onSeeked = (callback: Taro.InnerAudioContext.OnSeekedCallback = () => {}) => this.Instance?.addEventListener('seeked', callback as any)
offCanplay = (callback: Taro.InnerAudioContext.OnCanplayCallback = () => {}) => this.Instance?.removeEventListener('canplay', callback as any)
offPlay = (callback: Taro.InnerAudioContext.OnPlayCallback = () => {}) => this.Instance?.removeEventListener('play', callback as any)
offPause = (callback: Taro.InnerAudioContext.OnPauseCallback = () => {}) => this.Instance?.removeEventListener('pause', callback as any)
offStop = (callback: Taro.InnerAudioContext.OnStopCallback = () => {}) => this.stopStack.remove(callback)
offEnded = (callback: Taro.InnerAudioContext.OnEndedCallback = () => {}) => this.Instance?.removeEventListener('ended', callback as any)
offTimeUpdate = (callback: Taro.InnerAudioContext.OnTimeUpdateCallback = () => {}) => this.Instance?.removeEventListener('timeupdate', callback as any)
offError = (callback: Taro.InnerAudioContext.OnErrorCallback = () => {}) => this.errorStack.remove(callback)
offWaiting = (callback: Taro.InnerAudioContext.OnWaitingCallback = () => {}) => this.Instance?.removeEventListener('waiting', callback as any)
offSeeking = (callback: Taro.InnerAudioContext.OnSeekingCallback = () => {}) => this.Instance?.removeEventListener('seeking', callback as any)
offSeeked = (callback: Taro.InnerAudioContext.OnSeekedCallback = () => {}) => this.Instance?.removeEventListener('seeked', callback as any)
onWaiting = (callback: Taro.InnerAudioContext.OnWaitingCallback = () => {}) => this.addListener('waiting', callback as any)
onSeeking = (callback: Taro.InnerAudioContext.OnSeekingCallback = () => {}) => this.addListener('seeking', callback as any)
onSeeked = (callback: Taro.InnerAudioContext.OnSeekedCallback = () => {}) => this.addListener('seeked', callback as any)
offCanplay = (callback?: Taro.InnerAudioContext.OnCanplayCallback) => this.removeListener('canplay', callback as any)
offPlay = (callback?: Taro.InnerAudioContext.OnPlayCallback) => this.removeListener('play', callback as any)
offPause = (callback?: Taro.InnerAudioContext.OnPauseCallback) => this.removeListener('pause', callback as any)
offStop = (callback?: Taro.InnerAudioContext.OnStopCallback) => this.stopStack.remove(callback)
offEnded = (callback?: Taro.InnerAudioContext.OnEndedCallback) => this.removeListener('ended', callback as any)
offTimeUpdate = (callback?: Taro.InnerAudioContext.OnTimeUpdateCallback) => this.removeListener('timeupdate', callback as any)
offError = (callback?: Taro.InnerAudioContext.OnErrorCallback) => this.errorStack.remove(callback)
offWaiting = (callback?: Taro.InnerAudioContext.OnWaitingCallback) => this.removeListener('waiting', callback as any)
offSeeking = (callback?: Taro.InnerAudioContext.OnSeekingCallback) => this.removeListener('seeking', callback as any)
offSeeked = (callback?: Taro.InnerAudioContext.OnSeekedCallback) => this.removeListener('seeked', callback as any)
}
Loading