You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确保缓存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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 03:24:21