import Taro from "@tarojs/taro";
import { decode } from './index'
let audioCtx:Taro.WebAudioContext | AudioContext;
if (process.env.TARO_ENV === 'h5') {
  audioCtx = new AudioContext()
}else {
  audioCtx = Taro.createWebAudioContext()
}
let source: AudioBufferSourceNode;
export const useBase64AudioPlayer = () => {
  let endCallback: ()=>void;
  const playAudio = (base64Str: string): Promise<AudioBufferSourceNode | null> => {
    const audioArrayBuffer = decode(base64Str)
    // 解码ArrayBuffer为AudioBuffer
    return new Promise((resolve) => {
      // @ts-ignore
      Taro.setInnerAudioOption({
        obeyMuteSwitch: false,
      })
      audioCtx.decodeAudioData(audioArrayBuffer, (decodedAudioBuffer) => {
        source = audioCtx.createBufferSource();
        source.buffer = decodedAudioBuffer;

        // 连接到输出目的地
        // @ts-ignore
        source.connect(audioCtx.destination);
        // 开始播放
        source.start(0);
        source.onended = () => {
          endCallback && endCallback()
          console.log('播放结束');
        };
        resolve(source)
      }, (error) => {
        console.error('音频解码失败', error);
        resolve(null)
      });
    })
  }

  const stopAudio = ()=> {
    source && source.stop();
  }
  const onEnded = (cb: () => void) => {
    endCallback = cb
  }

  return {
    playAudio,
    stopAudio,
    onEnded,
  }
}
