useAudio.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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('swiper-change',() => {
  51. handleStop();
  52. })
  53. // 解析关闭 停止播放
  54. uni.$on('question-jiexi-close',() => {
  55. handleStop();
  56. })
  57. // 交卷 停止播放
  58. uni.$on('unitTest-submit', () => {
  59. handleStop();
  60. })
  61. return {
  62. options,
  63. handlePlay,
  64. handleStop,
  65. innerAudioContext
  66. }
  67. }