index.vue 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <template></template>
  2. <script setup>
  3. import { onReady, onLoad, onUnload, onShow, onNavigationBarButtonTap, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
  4. import { defineComponent, getCurrentInstance, inject, nextTick, onMounted, watchEffect, ref } from "vue";
  5. const emit = defineEmits(["onEnded", "onError"]);
  6. const props = defineProps({
  7. //播放原地址
  8. audioUrl: {
  9. type: String,
  10. defualt: "",
  11. },
  12. //是否开启
  13. audioBool: {
  14. type: Boolean,
  15. defualt: "",
  16. },
  17. });
  18. const isPlay = ref(false);
  19. const innerAudio = ref(null);
  20. function handleTTS() {
  21. if (!audioBool) {
  22. return;
  23. }
  24. if (innerAudio.value) {
  25. try {
  26. innerAudio.value.pause();
  27. innerAudio.value.destroy();
  28. innerAudio.value = null;
  29. } catch (e) {
  30. //TODO handle the exception
  31. }
  32. }
  33. innerAudio.value = uni.createInnerAudioContext();
  34. innerAudio.value.autoplay = true;
  35. innerAudio.value.volume = 1;
  36. innerAudio.value.src = props.audioUrl;
  37. innerAudio.value.onPlay(() => {
  38. console.log("开始播放");
  39. });
  40. innerAudio.value.onEnded((res) => {
  41. console.log("音频播放结束");
  42. isPlay.value = false;
  43. });
  44. innerAudio.value.onError((res) => {
  45. console.log("音频播放出错" + res);
  46. console.log(res.errCode);
  47. });
  48. innerAudio.value.play();
  49. }
  50. watchEffect(() => {
  51. if (props.audioUrl) {
  52. handleTTS();
  53. }
  54. });
  55. onUnload(() => {
  56. if (innerAudio.value) {
  57. innerAudio.value.stop();
  58. innerAudio.value.destroy();
  59. }
  60. });
  61. </script>
  62. <style lang="scss" scoped></style>