diff --git a/aiChat/mixins/chatMixinsV2.js b/aiChat/mixins/chatMixinsV2.js index 41023d3..224950a 100644 --- a/aiChat/mixins/chatMixinsV2.js +++ b/aiChat/mixins/chatMixinsV2.js @@ -84,6 +84,9 @@ export const chatMixinsV2 = { this.audioStopHandle() this.closeWsFn() }, + onHide() { + this.audioStopHandle() + }, created() { const _this = this uni.getSystemInfo({ @@ -671,6 +674,18 @@ export const chatMixinsV2 = { }) }, audioStopHandle() { + // 强制关闭微信小程序背景音频 + try { + const bgAudio = wx.getBackgroundAudioManager ? wx.getBackgroundAudioManager() : null + if (bgAudio && typeof bgAudio.stop === 'function') { + bgAudio.stop() + bgAudio.src = '' + bgAudio.title = '' + } + } catch (e) { + console.warn('stop background audio failed', e) + } + this.audioPlayId = '' // Fix bug#4049 this.audioAyy = [] if (this.audioContext) { @@ -679,11 +694,6 @@ export const chatMixinsV2 = { this.audioContext = null } this.isPlayAudio = false - - // 强制关闭微信小程序背景音频 - if (typeof wx !== 'undefined' && wx.getBackgroundAudioManager) { - wx.getBackgroundAudioManager().stop() - } }, ttsHandle(item) { this.audioAyy = [] @@ -762,25 +772,46 @@ export const chatMixinsV2 = { } }, playNextChunk() { - if (this.audioAyy.length > 0 && this.audioPlayId) { - const src = this.audioAyy.shift() - this.isPlayAudio = true - const audioContext = uni.createInnerAudioContext({ - // 是否使用 WebAudio 作为底层音频驱动,默认关闭。对于短音频、播放频繁的音频建议开启此选项,开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长,因此对于长音频建议关闭此选项 - useWebAudioImplement: false - }) - this.audioContext = audioContext - audioContext.src = src - audioContext.onEnded(() => { - audioContext.destroy() - this.playNextChunk() - }) - audioContext.play() - console.log('------------src:' + src) - } else { - console.log('------------end') + if (!this.audioAyy.length || !this.audioPlayId) { this.isPlayAudio = false + return } + + // 销毁旧实例 + if (this.audioContext) { + this.audioContext.stop() + this.audioContext.destroy() + this.audioContext = null + } + + const src = this.audioAyy.shift() + this.isPlayAudio = true + + const audioContext = uni.createInnerAudioContext({ + useWebAudioImplement: true // 短音频建议 true + }) + + this.audioContext = audioContext + audioContext.src = src + + audioContext.onPlay(() => { + console.log('audio play:', src) + }) + + audioContext.onEnded(() => { + this.audioContext = null + audioContext.destroy() + this.playNextChunk() + }) + + audioContext.onError((err) => { + console.error('audio error', err) + this.audioContext = null + audioContext.destroy() + this.playNextChunk() + }) + + audioContext.play() }, bottomToolClickHandle(item) { // 非界面跳转的需要校验登录状态 diff --git a/aiChat/views/index.vue b/aiChat/views/index.vue index 8d0a181..e43ff28 100644 --- a/aiChat/views/index.vue +++ b/aiChat/views/index.vue @@ -693,6 +693,7 @@ export default { } uni.removeStorageSync('addNewChat') } + this.audioStopHandle() }, methods: { extraReqFn() {