var audio = { innerAudioContext: null, audioSrc: "", audioStatus: 0, // 音频状态 0: 未播放 1: 播放中 2: 暂停 playAudio(src, loop = true) { console.log(`[audio] playAudio: ${src} , loop: ${loop}`); if (src == '') { console.log(`[audio] playAudio: src参数为空!`); return; } this.destroy(); this.audioSrc = src; try { this.innerAudioContext = uni.createInnerAudioContext(); this.innerAudioContext.autoplay = true; this.innerAudioContext.loop = loop; // this.innerAudioContext.obeyMuteSwitch = false; this.innerAudioContext.volume = 0.5; // this.innerAudioContext.sessionCategory = "soloAmbient"; this.innerAudioContext.src = this.audioSrc; this.innerAudioContext.onPlay(() => { console.log('[audio] 开始播放', this.audioSrc); this.audioStatus = 1; // 音频状态 0: 未播放 1: 播放中 2: 暂停 }); this.innerAudioContext.onError((err) => { console.log('[audio] playAudio onError:', err); this.audioStatus = 0; // 音频状态 0: 未播放 1: 播放中 2: 暂停 // uni.showToast({ // title: 'err:' + JSON.stringify(err), // icon: 'none', // duration: 5000 // }); }); } catch (e) { console.log('[audio] playAudio err:', e); // uni.showToast({ // title: 'e:' + JSON.stringify(e), // icon: 'none', // duration: 5000 // }); } }, play() { console.log('[audio] play()'); if (this.audioSrc != "") { this.innerAudioContext.play(); this.audioStatus = 1; // 音频状态 0: 未播放 1: 播放中 2: 暂停 } }, pause() { console.log('[audio] pause()'); if (this.audioSrc != "") { this.innerAudioContext.pause(); this.audioStatus = 2; // 音频状态 0: 未播放 1: 播放中 2: 暂停 } }, destroy() { if (this.innerAudioContext) { try { this.innerAudioContext.pause(); this.innerAudioContext.destroy(); this.innerAudioContext = null; this.audioStatus = 0; // 音频状态 0: 未播放 1: 播放中 2: 暂停 } catch (e) { console.log('[audio] destroy err:', e); // uni.showToast({ // title: 'e2:' + JSON.stringify(e), // icon: 'none', // duration: 5000 // }); } } } } export default audio;