useAudio.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import {nextTick, ref} from "vue";
  2. import { debounce } from "@/utils/common";
  3. export function useAudio() {
  4. const innerAudioContext = ref(null);
  5. const options = ref(null);
  6. function createAudio(audioUrl) {
  7. const innerAudioContext = uni.createInnerAudioContext();
  8. innerAudioContext.autoplay = false;
  9. innerAudioContext.src = audioUrl;
  10. innerAudioContext.onPlay(() => {
  11. // 播放
  12. uni.$emit('yy-audio-playing', options);
  13. });
  14. innerAudioContext.onError((res) => {
  15. uni.$emit('yy-audio-error')
  16. });
  17. innerAudioContext.onEnded(() => {
  18. // 播放结束
  19. uni.$emit('yy-audio-end',options)
  20. })
  21. return innerAudioContext;
  22. }
  23. function changeSource(url) {
  24. innerAudioContext.src= url;
  25. innerAudioContext.currentTime = 0;
  26. }
  27. const debuncePlay = debounce((myOption) => {
  28. innerAudioContext.value = createAudio(myOption.url);
  29. innerAudioContext.value.play()
  30. },50)
  31. function handlePlay(data) {
  32. if (innerAudioContext.value) {
  33. innerAudioContext.value.stop();
  34. innerAudioContext.value.destroy();
  35. innerAudioContext.value = null;
  36. uni.$emit('destory-stop')
  37. }
  38. options.value = data;
  39. debuncePlay(data);
  40. }
  41. function handleStop() {
  42. // console.log('stop')
  43. if (innerAudioContext.value) {
  44. innerAudioContext.value.destroy();
  45. innerAudioContext.value = null;
  46. uni.$emit('destory-stop')
  47. }
  48. }
  49. // 离开当前页面 停止播放
  50. uni.$on('back-outpage',() => {
  51. handleStop();
  52. })
  53. // 播放过程中点击同一个视频触发终止
  54. uni.$on('repeat-play-to-stop',() => {
  55. handleStop();
  56. })
  57. // 试题切换停止播放
  58. uni.$on('swiper-change',() => {
  59. handleStop();
  60. })
  61. // 解析关闭 停止播放
  62. uni.$on('question-jiexi-close',() => {
  63. handleStop();
  64. })
  65. // 交卷 停止播放
  66. uni.$on('unitTest-submit', () => {
  67. handleStop();
  68. })
  69. return {
  70. options,
  71. handlePlay,
  72. handleStop,
  73. innerAudioContext
  74. }
  75. }