<template></template>
<script setup>
import { onReady, onLoad, onUnload, onShow, onNavigationBarButtonTap, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
import { defineComponent, getCurrentInstance, inject, nextTick, onMounted, watchEffect, ref } from "vue";

const emit = defineEmits(["onEnded", "onError"]);
const props = defineProps({
  //播放原地址
  audioUrl: {
    type: String,
    defualt: "",
  },
  //是否开启
  audioBool: {
    type: Boolean,
    defualt: "",
  },
});

const isPlay = ref(false);
const innerAudio = ref(null);

function handleTTS() {
  if (!audioBool) {
    return;
  }

  if (innerAudio.value) {
    try {
      innerAudio.value.pause();
      innerAudio.value.destroy();
      innerAudio.value = null;
    } catch (e) {
      //TODO handle the exception
    }
  }

  innerAudio.value = uni.createInnerAudioContext();
  innerAudio.value.autoplay = true;
  innerAudio.value.volume = 1;
  innerAudio.value.src = props.audioUrl;
  innerAudio.value.onPlay(() => {
    console.log("开始播放");
  });
  innerAudio.value.onEnded((res) => {
    console.log("音频播放结束");
    isPlay.value = false;
  });
  innerAudio.value.onError((res) => {
    console.log("音频播放出错" + res);
    console.log(res.errCode);
  });

  innerAudio.value.play();
}

watchEffect(() => {
  if (props.audioUrl) {
    handleTTS();
  }
});

onUnload(() => {
  if (innerAudio.value) {
    innerAudio.value.stop();
    innerAudio.value.destroy();
  }
});
</script>
<style lang="scss" scoped></style>
