Skip to content

Commit 1d92724

Browse files
authored
fix(app-plus): 避免背景音频多次累计触发,和微信不符 #5926 (#5941)
* wip(app-plus): 避免背景音频多次累计触发,和微信不符 #5926 * fix: 定时器优化
1 parent 191871d commit 1d92724

File tree

1 file changed

+49
-25
lines changed

1 file changed

+49
-25
lines changed

packages/uni-app-plus/src/service/api/context/getBackgroundAudioManager.ts

Lines changed: 49 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,17 @@ const eventNames: eventNames[] = [
6565
'waiting',
6666
]
6767

68-
const callbacks: Record<eventNames, Function[]> = {
69-
canplay: [],
70-
play: [],
71-
pause: [],
72-
stop: [],
73-
ended: [],
74-
timeUpdate: [],
75-
prev: [],
76-
next: [],
77-
error: [],
78-
waiting: [],
68+
const callbacks: Record<eventNames, Function | null> = {
69+
canplay: null,
70+
play: null,
71+
pause: null,
72+
stop: null,
73+
ended: null,
74+
timeUpdate: null,
75+
prev: null,
76+
next: null,
77+
error: null,
78+
waiting: null,
7979
}
8080

8181
let audio: Audio
@@ -119,7 +119,9 @@ function initMusic() {
119119
// 添加 isStopped 属性是为了解决 安卓设备停止播放后获取播放进度不正确的问题
120120
if (event === 'play') {
121121
audio.isStopped = false
122-
startTimeUpdateTimer()
122+
if (callbacks.timeUpdate) {
123+
startTimeUpdateTimer()
124+
}
123125
} else if (event === 'stop') {
124126
audio.isStopped = true
125127
}
@@ -298,25 +300,47 @@ function onBackgroundAudioStateChange({
298300
errCode?: number
299301
dataUrl?: string
300302
}) {
301-
callbacks[state].forEach((callback) => {
302-
if (isFunction(callback)) {
303-
callback(
304-
state === 'error'
305-
? {
306-
errMsg,
307-
errCode,
308-
}
309-
: {}
310-
)
311-
}
312-
})
303+
const callback = callbacks[state]
304+
if (isFunction(callback)) {
305+
callback(
306+
state === 'error'
307+
? {
308+
errMsg,
309+
errCode,
310+
}
311+
: {}
312+
)
313+
}
313314
}
314315

315316
const onInitBackgroundAudioManager = /*#__PURE__*/ once(() => {
316317
eventNames.forEach((item) => {
317318
BackgroundAudioManager.prototype[`on${capitalize(item)}` as onEventNames] =
318319
function (callback: Function) {
319-
callbacks[item].push(callback)
320+
// Align with other platforms: keep only the latest listener
321+
callbacks[item] = callback
322+
if (
323+
item === 'timeUpdate' &&
324+
audio &&
325+
!audio.isPaused() &&
326+
!audio.isStopped
327+
) {
328+
if (timeUpdateTimer !== null) {
329+
clearInterval(timeUpdateTimer)
330+
}
331+
timeUpdateTimer = setInterval(() => {
332+
onBackgroundAudioStateChange({ state: 'timeUpdate' })
333+
}, TIME_UPDATE)
334+
}
335+
}
336+
BackgroundAudioManager.prototype[`off${capitalize(item)}` as any] =
337+
function (callback?: Function) {
338+
if (!callback || callbacks[item] === callback) {
339+
callbacks[item] = null
340+
if (item === 'timeUpdate') {
341+
stopTimeUpdateTimer()
342+
}
343+
}
320344
}
321345
})
322346
})

0 commit comments

Comments
 (0)