部分获取音频内容时编码失败



我使用fetch API来进行API调用和部分接收音频文件(206)。当我尝试将结果转换为AudioBuffer并使用音频播放时,我得到以下错误:

DOMException: The buffer passed to decodeAudioData包含无效内容,无法成功解码。

下面是简化后的代码库:
const context = new AudioContext();
fetch(
'API/ENDPOINT',
{
method: 'GET',
headers: {
'Content-Type': 'audio/mpeg',
'range': `bytes=${range[0]}-${range[1]}`,
},
}
)
.then((partialContent) => partialContent.arrayBuffer())
.then((arrayBuffer) => context.decodeAudioData(arrayBuffer))
.then((audioBuffer) => {
console.log('@todo: Use the buffer to play the sound');
})
.catch(console.log);

我错在哪里?

问题是decodeAudioData()只能解码完整的文件。但看起来你用的是mp3。如果你在帧边界切割它们,你可以让decodeAudioData()相信它处理的是完整的文件。Rich-Harris/phonograph项目就是这样做的。

解决这个问题的更现代的方法是使用WebCodecs,它允许你对音频块进行解码。

最新更新