useYinbiao.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. isAutoPlaying.value = false;
  31. }
  32. }
  33. function initListen() {
  34. uni.$on('danci-audio-ended', (mCode) => {
  35. if (code !== mCode) {
  36. isAutoPlaying.value = false;
  37. return;
  38. }
  39. if (current.value<list.value.length-1) {
  40. current.value = current.value+1;
  41. // 继续播放第二音频
  42. handlePlay();
  43. } else {
  44. // 播放结束
  45. isAutoPlaying.value = false;
  46. }
  47. })
  48. }
  49. function removeListen() {
  50. uni.$off('danci-audio-ended')
  51. }
  52. function playYinbiaoAuto(clist) {
  53. current.value = 0
  54. list.value = clist;
  55. // 执行首次播放
  56. handlePlay();
  57. }
  58. // 初始化首次监听
  59. initListen();
  60. return {
  61. playYinbiaoAuto,
  62. isAutoPlaying,
  63. removeListen
  64. }
  65. }