后端传来是 base64-encoded 的 mp3 音频的字符串,码率、声道这些信息( sampleRate 、numChannels 、bitsPerSample 、dataLength )不知道,直接放在<audio>中播放是正常的:
<audio controls>
<source src="data:audio/mpeg;base64, base64-encoded-string" type="audio/mpeg">
</audio>
重新解码作为 blob 播放,放出来就很多杂音,这中情况是哪里的问题?
<script type="text/javascript">
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const decoder = new TextDecoder("utf-8");
function base64ToArrayBuffer(base64) {
const binary = atob(base64);
const len = binary.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
function playAudioChunk(base64) {
const arrayBuffer = base64ToArrayBuffer(base64);
audioContext.decodeAudioData(arrayBuffer).then((audioBuffer) => {
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start(0);
}).catch((err) => {
console.error("Error decoding audio data", err);
});
}
// ws-connection ...
playAudioChunk(base64-encoded-string);
</script>
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.