You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
2.1 KiB
92 lines
2.1 KiB
2 months ago
|
// 全局音频管理工具
|
||
|
export const GlobalAudioManager = {
|
||
|
// 获取当前全局音频实例
|
||
|
getCurrentAudio() {
|
||
|
const app = getApp();
|
||
|
return app && app.globalData ? app.globalData.currentAudio : null;
|
||
|
},
|
||
|
|
||
|
// 设置全局音频实例
|
||
|
setCurrentAudio(audioContext) {
|
||
|
const app = getApp();
|
||
|
if (app && app.globalData) {
|
||
|
app.globalData.currentAudio = audioContext;
|
||
|
}
|
||
|
},
|
||
|
|
||
|
// 清除全局音频实例
|
||
|
clearCurrentAudio() {
|
||
|
const app = getApp();
|
||
|
if (app && app.globalData) {
|
||
|
if (app.globalData.currentAudio) {
|
||
|
try {
|
||
|
app.globalData.currentAudio.stop();
|
||
|
app.globalData.currentAudio.destroy();
|
||
|
} catch (error) {
|
||
|
console.error('销毁全局音频失败:', error);
|
||
|
}
|
||
|
}
|
||
|
app.globalData.currentAudio = null;
|
||
|
}
|
||
|
},
|
||
|
|
||
|
// 检查是否有音频在播放
|
||
|
isAudioPlaying() {
|
||
|
const audio = this.getCurrentAudio();
|
||
|
return audio && !audio.paused;
|
||
|
},
|
||
|
|
||
|
// 暂停当前音频
|
||
|
pauseCurrentAudio() {
|
||
|
const audio = this.getCurrentAudio();
|
||
|
if (audio && !audio.paused) {
|
||
|
audio.pause();
|
||
|
// 通知状态变化
|
||
|
this.notifyAudioStateChange(false);
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
},
|
||
|
|
||
|
// 播放当前音频
|
||
|
playCurrentAudio() {
|
||
|
const audio = this.getCurrentAudio();
|
||
|
if (audio && audio.paused) {
|
||
|
audio.play();
|
||
|
// 通知状态变化
|
||
|
this.notifyAudioStateChange(true);
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
},
|
||
|
|
||
|
// 停止当前音频
|
||
|
stopCurrentAudio() {
|
||
|
const audio = this.getCurrentAudio();
|
||
|
if (audio) {
|
||
|
audio.stop();
|
||
|
// 通知状态变化
|
||
|
this.notifyAudioStateChange(false);
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
},
|
||
|
|
||
|
// 通知音频状态变化
|
||
|
notifyAudioStateChange(isPlaying) {
|
||
|
if (typeof uni !== 'undefined') {
|
||
|
uni.$emit('audioPlaying', isPlaying);
|
||
|
}
|
||
|
},
|
||
|
|
||
|
// 获取当前音频的src
|
||
|
getCurrentAudioSrc() {
|
||
|
const audio = this.getCurrentAudio();
|
||
|
return audio ? audio.src : null;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
// 将工具挂载到全局
|
||
|
if (typeof uni !== 'undefined') {
|
||
|
uni.$globalAudio = GlobalAudioManager;
|
||
|
}
|