<!-- /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>