123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- import {
- reactive,
- ref
- } from 'vue';
- import {
- onHide,
- onUnload
- } from "@dcloudio/uni-app"
- import {
- nextTick
- } from 'vue';
- let audioContext = null;
- let code = null; // 身份标识
- audioContext = uni.createInnerAudioContext(); // 单例模式[3](@ref)
- audioContext.onEnded(() => {
- // console.log('触发播放结束')
- // 播放结束
- uni.$emit('danci-audio-ended')
- })
- audioContext.onPlay(() => {
- // 播放
- // console.log('播放事件:', code)
- uni.$emit('danci-audio-play', code);
- });
- export class audioPlayer {
- // 播放音频
- play(path, code1) {
- // console.log('播放文件地址', path)
- code = code1;
- if (audioContext.src === path && !audioContext.paused) return;
- audioContext.src = path;
- audioContext.play();
- }
- // 暂停播放
- pause() {
- audioContext?.pause();
- }
- // 停止播放(释放资源)
- stop() {
- audioContext?.stop();
- audioContext = null;
- }
- }
- export function useAudioCache() {
- const cacheMapKey = 'audio_cache_map'; // Storage 中缓存映射的键名
- // 下载并缓存音频
- async function cacheAudio(url) {
- try {
- let cacheMap = uni.getStorageSync(cacheMapKey) || {};
- if (cacheMap[url]) {
- // console.log('已缓存音频地址', cacheMap[url])
- return cacheMap[url]; // 返回有效缓存路径
- }
- // 3. 下载音频文件
- const {
- tempFilePath
- } = await new Promise((resolve, reject) => {
- uni.downloadFile({
- url,
- success: resolve,
- fail: reject
- });
- });
- if (!tempFilePath.includes('.mp3')) {
- // console.log(`文件下载失败${url}`)
- return null;
- }
- // 4. 持久化存储到本地
- const savedFilePath = tempFilePath; // 跨平台安全路径[2](@ref)
- await uni.saveFile({
- tempFilePath,
- toSavedFilePath: savedFilePath
- });
- cacheMap[url] = savedFilePath;
- uni.setStorageSync(cacheMapKey, cacheMap);
- // console.log('当前音频地址', savedFilePath)
- return savedFilePath;
- } catch (err) {
- // console.error('音频缓存失败:', err);
- return null;
- }
- }
- function clearAudioCache() {
- // uni.setStorageSync(cacheMapKey, {})
- const cacheMap = uni.getStorageSync(cacheMapKey) || {};
- Object.entries(cacheMap).forEach(([key, path]) => {
- uni.removeSavedFile({
- filePath: path
- }); // 删除文件
- delete cacheMap[key];
- })
- // console.log('已清理完成', cacheMap)
- uni.setStorageSync(cacheMapKey, cacheMap)
- }
- return {
- cacheAudio,
- clearAudioCache
- }
- }
|