vue实现audio局部缓存
实现 Vue 中 Audio 的局部缓存
使用 Service Worker 缓存音频文件
Service Worker 可以拦截网络请求并缓存资源。注册一个 Service Worker 并配置缓存策略,将音频文件存储在 Cache API 中。
// sw.js
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('audio-cache').then((cache) => {
return cache.addAll([
'/path/to/audio1.mp3',
'/path/to/audio2.mp3'
]);
})
);
});
self.addEventListener('fetch', (event) => {
if (event.request.url.includes('/path/to/audio')) {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
}
});
使用 localStorage 或 IndexedDB 存储音频数据
对于较小的音频文件,可以将其转换为 Base64 并存储在 localStorage 中。对于较大的文件,使用 IndexedDB 更合适。
// 存储音频到 localStorage
function cacheAudioToLocalStorage(key, audioBlob) {
const reader = new FileReader();
reader.onload = () => {
localStorage.setItem(key, reader.result);
};
reader.readAsDataURL(audioBlob);
}
// 从 localStorage 读取音频
function getCachedAudio(key) {
return localStorage.getItem(key);
}
使用 Vue 组件管理音频缓存
创建一个 Vue 组件来管理音频的加载和缓存逻辑,确保在音频播放前检查缓存。
<template>
<audio ref="audioPlayer" controls></audio>
</template>
<script>
export default {
methods: {
async playAudio(url) {
const cachedAudio = localStorage.getItem(url);
if (cachedAudio) {
this.$refs.audioPlayer.src = cachedAudio;
} else {
const response = await fetch(url);
const blob = await response.blob();
cacheAudioToLocalStorage(url, blob);
this.$refs.audioPlayer.src = URL.createObjectURL(blob);
}
this.$refs.audioPlayer.play();
}
}
};
</script>
使用 PWA 技术增强缓存能力
结合 Vue PWA 插件(如 @vue/cli-plugin-pwa),可以更高效地管理缓存策略。在 vue.config.js 中配置缓存选项。
// vue.config.js
module.exports = {
pwa: {
workboxOptions: {
runtimeCaching: [
{
urlPattern: /\.mp3$/,
handler: 'CacheFirst',
options: {
cacheName: 'audio-cache',
expiration: {
maxEntries: 10,
maxAgeSeconds: 7 * 24 * 60 * 60
}
}
}
]
}
}
};
注意事项
- 缓存策略需根据音频文件大小和使用频率调整,避免占用过多存储空间。
- Service Worker 仅在 HTTPS 或 localhost 环境下生效。
- 及时清理过期缓存,防止存储空间被无效数据占用。







