useAudio.js 2.4 KB

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