import { useAudio as Audio } from '@/hooks'
const OSS_URL = import.meta.env.VITE_OSS_URL

const soundUrl = `${OSS_URL}/xuexiaole_clinet/sound/`

// const music = uni.createInnerAudioContext(); // 创建播放器对象
const playSwitches = ref([] as Ref<boolean>[])

const useAudio = function (needStatic?: boolean) {
  // 每个音频生成一个对应的 isPlay 状态
  const isPlay = ref(false)
  playSwitches.value.push(isPlay)

  const play = (url: string) => {
    playSwitches.value.forEach(item => (item.value = false)) // 关闭所有音频的isPlay
    isPlay.value = true
    Audio({
      url: needStatic ? soundUrl + url : url,
      autoplay: true,
      onEnded() {
        isPlay.value = false
      },
      onError() {
        isPlay.value = false
      },
    })
  }

  const stopAll = () => {
    playSwitches.value.forEach(item => (item.value = false))
    // music.stop();
  }

  const destroy = () => {
    // music.destroy();
  }

  return {
    isPlay,
    play,
    destroy,
    stopAll,
  }
}

export default useAudio
