useYinbiao.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import {ref} from "vue"
  2. import {
  3. audioPlayer,
  4. useAudioCache,
  5. } from "./useAudio.js";
  6. export function useYinBiaoAutoPlay () {
  7. const AudioP = new audioPlayer();
  8. const {
  9. cacheAudio,
  10. } = useAudioCache();
  11. const current = ref(0);
  12. const list = ref([]);
  13. let code = null;
  14. const isAutoPlaying = ref(false);
  15. async function handlePlay() {
  16. isAutoPlaying.value = true;
  17. code = new Date().getTime();
  18. const activeYin = {
  19. url: list.value[current.value].yinpin,
  20. code
  21. }
  22. const cachedPath = await cacheAudio(activeYin.url);
  23. if (cachedPath && cachedPath.includes('.mp3')) {
  24. AudioP.play(cachedPath, code);
  25. } else {
  26. uni.showToast({
  27. title: '音频加载失败',
  28. icon: 'none'
  29. });
  30. }
  31. }
  32. function initListen() {
  33. uni.$on('danci-audio-ended', (mCode) => {
  34. if (code !== mCode) {
  35. isAutoPlaying.value = false;
  36. return;
  37. }
  38. if (current.value<list.value.length-1) {
  39. current.value = current.value+1;
  40. // 继续播放第二音频
  41. handlePlay();
  42. } else {
  43. // 播放结束
  44. isAutoPlaying.value = false;
  45. }
  46. })
  47. }
  48. function removeListen() {
  49. uni.$off('danci-audio-ended')
  50. }
  51. function playYinbiaoAuto(clist) {
  52. current.value = 0
  53. list.value = clist;
  54. // 执行首次播放
  55. handlePlay();
  56. }
  57. // 初始化首次监听
  58. initListen();
  59. return {
  60. playYinbiaoAuto,
  61. isAutoPlaying,
  62. removeListen
  63. }
  64. }