useAudio.js 2.4 KB

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