Files
xk-client-wx/subPackages/chat/components/AudioPlayer.vue

89 lines
2.1 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!-- /components/AudioPlayer.vue -->
<script>
export default {
data() {
return {
currentAudio: null, // 当前播放的音频ID
audioContext: null, // 微信音频上下文
playing: false // 是否正在播放
};
},
methods: {
// 播放音频
play({ id, src }) {
// 如果当前正在播放同一音频,则暂停
if (this.currentAudio === id && this.playing) {
this.pause();
return;
}
// 如果当前播放的是其他音频,先停止
if (this.currentAudio && this.currentAudio !== id) {
this.stop();
}
// 创建新的音频上下文
this.audioContext = wx.createInnerAudioContext();
this.audioContext.src = src;
this.audioContext.play();
this.currentAudio = id;
this.playing = true;
this.$emit('play', id);
// 监听音频结束事件
this.audioContext.onEnded(() => {
this.playing = false;
this.currentAudio = null;
this.$emit('ended');
});
// 监听音频错误事件
this.audioContext.onError((err) => {
console.error('音频播放失败:', err);
this.playing = false;
this.currentAudio = null;
this.$emit('error', err);
});
},
// 暂停音频
pause() {
if (this.audioContext && this.playing) {
this.audioContext.pause();
this.playing = false;
this.$emit('pause');
}
},
// 停止音频
stop() {
if (this.audioContext) {
this.audioContext.stop();
this.audioContext.destroy();
this.audioContext = null;
this.playing = false;
this.currentAudio = null;
this.$emit('ended');
}
},
// 检查指定音频是否正在播放
isPlaying(audioId) {
return this.currentAudio === audioId && this.playing;
}
},
beforeDestroy() {
// 组件销毁时停止音频
if (this.audioContext) {
this.audioContext.stop();
this.audioContext.destroy();
}
}
};
</script>
<template>
<!-- 即使不需要渲染内容也需要保留一个空的 template -->
<div v-if="false"></div>
</template>