let audioContext = null;

export function playVoice(url) {
  if (audioContext) {
    try {
      audioContext.pause();
      audioContext.destroy();
      audioContext = null;
    } catch (e) {
      // TODO: Handle the exception
    }
  }
  audioContext = uni.createInnerAudioContext();
  audioContext.autoplay = true;
  audioContext.src = url;
  audioContext.onPlay(() => {
    console.log('开始播放');
  });
}

export function playSequentially(audioUrls) {
  if (audioUrls.length === 0) return;

  let currentIndex = 0;

  function playNext() {
    if (currentIndex < audioUrls.length) {
      playVoice(audioUrls[currentIndex]);
      audioContext.onEnded(() => {
        currentIndex++;
        playNext(); // 播放下一个音频
      });
    } else {
      audioContext.destroy(); // 播放完毕，清理
      audioContext = null;
    }
  }

  playNext(); // 开始播放
}

export const audioUrls = {
  failVoiceUrl: '../../static/fail.mp3',
  allSuccessVoiceUrl: '../../static/allSuccess.mp3',
  successVoiceUrl: '../../static/success.mp3',
  success2VoiceUrl: '../../static/success2.mp3',
  storeSuccessUrl: '../../static/storeSuccess.mp3',
  warningSuccessUrl: '../../static/success0.mp3'
};
