useYinbiao.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
  18. code = new Date().getTime();
  19. const activeYin = {
  20. url: list.value[current.value].yinpin,
  21. code
  22. }
  23. const cachedPath = await cacheAudio(activeYin.url);
  24. if (cachedPath && cachedPath.includes('.mp3')) {
  25. AudioP.play(cachedPath, code);
  26. } else {
  27. uni.showToast({
  28. title: '音频加载失败',
  29. icon: 'none'
  30. });
  31. isAutoPlaying.value = false;
  32. uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
  33. }
  34. }
  35. function initListen() {
  36. uni.$on('danci-audio-ended', (mCode) => {
  37. if (code !== mCode) {
  38. isAutoPlaying.value = false;
  39. uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
  40. return;
  41. }
  42. if (current.value<list.value.length-1) {
  43. current.value = current.value+1;
  44. // 继续播放第二音频
  45. handlePlay();
  46. } else {
  47. // 播放结束
  48. isAutoPlaying.value = false;
  49. uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
  50. }
  51. })
  52. }
  53. function removeListen() {
  54. uni.$off('danci-audio-ended')
  55. }
  56. function playYinbiaoAuto(clist) {
  57. isAutoPlaying.value = true;
  58. uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
  59. current.value = 0
  60. list.value = clist;
  61. // 执行首次播放
  62. handlePlay();
  63. }
  64. // 初始化首次监听
  65. initListen();
  66. return {
  67. playYinbiaoAuto,
  68. isAutoPlaying,
  69. removeListen
  70. }
  71. }