useAudio.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. // console.log('play111',data)
  33. if (innerAudioContext.value) {
  34. innerAudioContext.value.stop();
  35. innerAudioContext.value.destroy();
  36. innerAudioContext.value = null;
  37. uni.$emit('destory-stop')
  38. }
  39. options.value = data;
  40. debuncePlay(data);
  41. }
  42. function handleStop() {
  43. // console.log('stop')
  44. if (innerAudioContext.value) {
  45. innerAudioContext.value.destroy();
  46. innerAudioContext.value = null;
  47. uni.$emit('destory-stop')
  48. }
  49. }
  50. // 播放过程中点击同一个视频触发终止
  51. uni.$on('repeat-play-to-stop',() => {
  52. handleStop();
  53. })
  54. // 试题切换停止播放
  55. uni.$on('swiper-change',() => {
  56. handleStop();
  57. })
  58. // 解析关闭 停止播放
  59. uni.$on('question-jiexi-close',() => {
  60. handleStop();
  61. })
  62. // 交卷 停止播放
  63. uni.$on('unitTest-submit', () => {
  64. handleStop();
  65. })
  66. return {
  67. options,
  68. handlePlay,
  69. handleStop,
  70. innerAudioContext
  71. }
  72. }