前端 js 播放 base64 编码的 mp3,放出来杂音很大,请教是哪里出错了?

43 天前
 lisisi

后端传来是 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>
2013 次点击
所在节点    JavaScript
5 条回复
join
43 天前
你把两边编码都做一下转换。看看转出来的二进制是不是一致的。有可能是你的编解码转出的数据不一致造成的。
haah
43 天前
1 、https://superuser.com/questions/187424/re-encoding-of-mp3-files-and-quality-loss
2 、backend using PCM ,frontend using WAV 。
3 、frontend using pcm2wav method to play the audio object.

Just like the paddlespeech.
humbass
43 天前
之前搞 tts 语音合成,搞到吐。audio 组件自带解码。直接用 audiocontext 上下文,得还原成原始编码。然后通过 steam 写入,还要保证速率合适的写入。
ToDayMkCode
42 天前
之前有做过 https://github.com/WtecHtec/WorkNotes/tree/master/pyRTC
主要是采集、数据编码得一致,
iv8d
41 天前
看看原始的 pcm

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1147714

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX