后端传来是 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>