useAudio.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import {
  2. reactive,
  3. ref
  4. } from 'vue';
  5. import {
  6. onHide,
  7. onUnload
  8. } from "@dcloudio/uni-app"
  9. import {
  10. nextTick
  11. } from 'vue';
  12. let audioContext = null;
  13. let code = null; // 身份标识
  14. audioContext = uni.createInnerAudioContext(); // 单例模式[3](@ref)
  15. audioContext.onEnded(() => {
  16. // console.log('触发播放结束')
  17. // 播放结束
  18. uni.$emit('danci-audio-ended')
  19. })
  20. audioContext.onPlay(() => {
  21. // 播放
  22. // console.log('播放事件:', code)
  23. uni.$emit('danci-audio-play', code);
  24. });
  25. export class audioPlayer {
  26. // 播放音频
  27. play(path, code1) {
  28. // console.log('播放文件地址', path)
  29. code = code1;
  30. if (audioContext.src === path && !audioContext.paused) return;
  31. audioContext.src = path;
  32. audioContext.play();
  33. }
  34. // 暂停播放
  35. pause() {
  36. audioContext?.pause();
  37. }
  38. // 停止播放(释放资源)
  39. stop() {
  40. audioContext?.stop();
  41. audioContext = null;
  42. }
  43. }
  44. export function useAudioCache() {
  45. const cacheMapKey = 'audio_cache_map'; // Storage 中缓存映射的键名
  46. // 下载并缓存音频
  47. async function cacheAudio(url) {
  48. try {
  49. let cacheMap = uni.getStorageSync(cacheMapKey) || {};
  50. if (cacheMap[url]) {
  51. // console.log('已缓存音频地址', cacheMap[url])
  52. return cacheMap[url]; // 返回有效缓存路径
  53. }
  54. // 3. 下载音频文件
  55. const {
  56. tempFilePath
  57. } = await new Promise((resolve, reject) => {
  58. uni.downloadFile({
  59. url,
  60. success: resolve,
  61. fail: reject
  62. });
  63. });
  64. if (!tempFilePath.includes('.mp3')) {
  65. // console.log(`文件下载失败${url}`)
  66. return null;
  67. }
  68. // 4. 持久化存储到本地
  69. const savedFilePath = tempFilePath; // 跨平台安全路径[2](@ref)
  70. await uni.saveFile({
  71. tempFilePath,
  72. toSavedFilePath: savedFilePath
  73. });
  74. cacheMap[url] = savedFilePath;
  75. uni.setStorageSync(cacheMapKey, cacheMap);
  76. // console.log('当前音频地址', savedFilePath)
  77. return savedFilePath;
  78. } catch (err) {
  79. // console.error('音频缓存失败:', err);
  80. return null;
  81. }
  82. }
  83. function clearAudioCache() {
  84. // uni.setStorageSync(cacheMapKey, {})
  85. const cacheMap = uni.getStorageSync(cacheMapKey) || {};
  86. Object.entries(cacheMap).forEach(([key, path]) => {
  87. uni.removeSavedFile({
  88. filePath: path
  89. }); // 删除文件
  90. delete cacheMap[key];
  91. })
  92. // console.log('已清理完成', cacheMap)
  93. uni.setStorageSync(cacheMapKey, cacheMap)
  94. }
  95. return {
  96. cacheAudio,
  97. clearAudioCache
  98. }
  99. }