vue实现audio局部缓存
Vue 实现 Audio 局部缓存
使用 Service Worker 缓存音频文件
通过注册 Service Worker 可以实现音频文件的缓存。在 Vue 项目中,可以在 public 文件夹下创建 sw.js 文件,并在主入口文件中注册 Service Worker。
// public/sw.js
const CACHE_NAME = 'audio-cache-v1';
const urlsToCache = [
'/path/to/audio1.mp3',
'/path/to/audio2.mp3'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
在 Vue 的 main.js 中注册 Service Worker:
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(registration => console.log('SW registered'))
.catch(err => console.log('SW registration failed: ', err));
});
}
使用 LocalStorage 或 IndexedDB 存储音频数据
对于较小的音频文件,可以将其转换为 Base64 格式并存储在 LocalStorage 中。对于较大的文件,建议使用 IndexedDB。
// 将音频文件转换为 Base64
function audioToBase64(url, callback) {
fetch(url)
.then(response => response.blob())
.then(blob => {
const reader = new FileReader();
reader.onloadend = () => callback(reader.result);
reader.readAsDataURL(blob);
});
}
// 存储到 LocalStorage
audioToBase64('/path/to/audio.mp3', base64 => {
localStorage.setItem('audioCache', base64);
});
// 从 LocalStorage 读取
const audioBase64 = localStorage.getItem('audioCache');
const audio = new Audio(audioBase64);
audio.play();
使用 Vue 的响应式数据管理缓存状态
在 Vue 组件中,可以使用 data 或 Vuex 管理音频缓存状态。
export default {
data() {
return {
audioCache: {},
};
},
methods: {
cacheAudio(url) {
if (!this.audioCache[url]) {
const audio = new Audio(url);
this.audioCache[url] = audio;
}
return this.audioCache[url];
},
playAudio(url) {
const audio = this.cacheAudio(url);
audio.play();
},
},
};
使用第三方库简化缓存管理
可以使用 localforage 或 idb-keyval 等库简化 IndexedDB 操作。
import localforage from 'localforage';
// 存储音频文件
localforage.setItem('audio-key', audioBlob).then(() => {
console.log('Audio cached');
});
// 读取音频文件
localforage.getItem('audio-key').then(audioBlob => {
const audio = new Audio(URL.createObjectURL(audioBlob));
audio.play();
});
注意事项
- 缓存策略需根据音频文件大小和使用频率调整,避免占用过多存储空间。
- Service Worker 仅在 HTTPS 或 localhost 环境下生效。
- 对于动态音频文件,需在运行时更新缓存列表。







