gratitude.durian.xpcool.com/wechat-miniprogram/utils/AudioManager.js
2026-08-14 18:01:45 +08:00

173 lines
3.6 KiB
JavaScript

// utils/AudioManager.js - 音频管理器(微信小程序原生)
class AudioManager {
constructor() {
this.bgmContext = null;
this.sfxContexts = new Map();
this.voiceContext = null;
this.isMuted = false;
this.currentBGM = null;
}
/**
* 初始化音频上下文
*/
init() {
// BGM 音频上下文
this.bgmContext = wx.createInnerAudioContext();
this.bgmContext.loop = true;
this.bgmContext.autoplay = false;
// 语音音频上下文
this.voiceContext = wx.createInnerAudioContext();
this.voiceContext.loop = false;
this.voiceContext.autoplay = false;
console.log('[AudioManager] 初始化完成');
}
/**
* 播放背景音乐
* @param {string} src - 音频文件路径
*/
playBGM(src) {
if (this.isMuted) return;
if (this.currentBGM === src && !this.bgmContext.paused) {
return; // 已经在播放相同的BGM
}
this.stopBGM();
this.bgmContext.src = src;
this.bgmContext.play();
this.currentBGM = src;
console.log('[AudioManager] 播放BGM:', src);
}
/**
* 停止背景音乐
*/
stopBGM() {
if (this.bgmContext) {
this.bgmContext.stop();
this.currentBGM = null;
}
}
/**
* 播放音效
* @param {string} type - 音效类型
*/
playSFX(type) {
if (this.isMuted) return;
const sfxMap = {
'drop': '/audio/sfx_drop.mp3',
'merge': '/audio/sfx_merge.mp3',
'combo2': '/audio/sfx_combo2.mp3',
'combo3': '/audio/sfx_combo3.mp3',
'combo4': '/audio/sfx_combo4.mp3',
'combo5': '/audio/sfx_combo5.mp3',
'golden': '/audio/sfx_golden.mp3',
'clear': '/audio/sfx_clear.mp3',
'gameover': '/audio/sfx_gameover.mp3',
'revive': '/audio/sfx_revive.mp3'
};
const src = sfxMap[type];
if (!src) {
console.warn('[AudioManager] 未知音效类型:', type);
return;
}
// 复用或创建音效上下文
let context = this.sfxContexts.get(type);
if (!context) {
context = wx.createInnerAudioContext();
context.loop = false;
context.autoplay = false;
this.sfxContexts.set(type, context);
}
context.src = src;
context.play();
console.log('[AudioManager] 播放音效:', type);
}
/**
* 播放语音
* @param {string} src - 语音文件路径
*/
playVoice(src) {
if (this.isMuted) return;
this.stopVoice();
this.voiceContext.src = src;
this.voiceContext.play();
console.log('[AudioManager] 播放语音:', src);
}
/**
* 停止语音
*/
stopVoice() {
if (this.voiceContext) {
this.voiceContext.stop();
}
}
/**
* 静音/取消静音
*/
setMute(muted) {
this.isMuted = muted;
if (muted) {
this.stopBGM();
this.stopVoice();
// 停止所有音效
for (const context of this.sfxContexts.values()) {
context.stop();
}
} else {
// 恢复BGM
if (this.currentBGM) {
this.bgmContext.play();
}
}
console.log('[AudioManager] 静音:', muted);
}
/**
* 销毁所有音频资源
*/
destroy() {
if (this.bgmContext) {
this.bgmContext.destroy();
}
if (this.voiceContext) {
this.voiceContext.destroy();
}
for (const context of this.sfxContexts.values()) {
context.destroy();
}
this.sfxContexts.clear();
console.log('[AudioManager] 资源已销毁');
}
}
// 单例导出
const audioManager = new AudioManager();
module.exports = audioManager;