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.
 
 
 
 

108 lines
2.1 KiB

let instance = null;
class AudioManager {
constructor() {
if (instance) {
return instance;
}
this.audioContext = null;
this.isPlaying = false;
this.userDisabled = false;
this.initialized = false;
try {
const musicState = uni.getStorageSync('musicState') || {};
this.userDisabled = musicState.userDisabled === true;
} catch (e) {
console.error('读取音乐状态失败:', e);
}
instance = this;
}
init() {
if (this.initialized) return this;
this.audioContext = uni.createInnerAudioContext();
this.audioContext.src = 'https://des.dayunyuanjian.cn/epicSoul/taozi/bg.m4a';
this.audioContext.loop = true;
this.audioContext.onPlay(() => {
this.isPlaying = true;
this._notifyStateChange();
});
this.audioContext.onPause(() => {
this.isPlaying = false;
this._notifyStateChange();
});
this.audioContext.onStop(() => {
this.isPlaying = false;
this._notifyStateChange();
});
this.audioContext.onError((res) => {
this.isPlaying = false;
this._notifyStateChange();
});
this.initialized = true;
return this;
}
play() {
if (this.userDisabled) return;
this.init();
if (!this.isPlaying) {
this.audioContext.play();
}
}
pause() {
if (!this.initialized || !this.isPlaying) return;
this.audioContext.pause();
}
togglePlay() {
this.init();
if (this.isPlaying) {
this.pause();
this.userDisabled = true;
} else {
this.userDisabled = false;
this.play();
}
try {
uni.setStorageSync('musicState', {
userDisabled: this.userDisabled
});
} catch (e) {
console.error('保存音乐状态失败:', e);
}
return this.isPlaying;
}
_notifyStateChange() {
uni.$emit('audioStateChanged', {
isPlaying: this.isPlaying,
userDisabled: this.userDisabled
});
}
getPlayingStatus() {
return this.isPlaying;
}
getUserDisabled() {
return this.userDisabled;
}
}
export default new AudioManager();