如何确保缓存MP3的Content-Type为audio/mp3并在浏览器播放缓存文件?
解决方案
1. 确保缓存的MP3文件Content-Type为audio/mp3
cache.add()会直接缓存服务器返回的原始响应头,无法修改内容类型。要实现自定义Content-Type,需要手动发起请求、修改响应后再存入缓存:
const request = URL_TO_MY_MP3_FILE; caches.open("my-cache").then(async (cache) => { // 获取原始响应 const originalResponse = await fetch(request); // 复制响应并修改Content-Type const modifiedResponse = new Response(originalResponse.body, { headers: new Headers(originalResponse.headers), status: originalResponse.status, statusText: originalResponse.statusText }); modifiedResponse.headers.set('Content-Type', 'audio/mp3'); // 将修改后的响应存入缓存 await cache.put(request, modifiedResponse); });
2. 正确从缓存获取并播放MP3
缓存返回的result是Response对象,Audio构造函数不支持直接传入ReadableStream,需要将响应转为Blob并生成可访问的Object URL:
const request = URL_TO_MY_MP3_FILE; caches.open("my-cache").then(async (cache) => { const cachedResponse = await cache.match(request); if (!cachedResponse) { console.log("缓存中未找到目标音频文件"); return; } // 将响应转为Blob格式 const audioBlob = await cachedResponse.blob(); // 生成Audio可识别的Object URL const audioUrl = URL.createObjectURL(audioBlob); this.audio = new Audio(audioUrl); try { await this.audio.play(); console.log('success!'); } catch (error) { console.log(error); // 播放失败时及时释放URL避免内存泄漏 URL.revokeObjectURL(audioUrl); } // 音频播放结束后释放URL this.audio.addEventListener('ended', () => { URL.revokeObjectURL(audioUrl); }); });
内容的提问来源于stack exchange,提问作者etayluz
相关产品推荐
相关产品推荐

