Web Audio Api:通过套接字从 Nodejs 服务器播放数据块的正确方法

Val*_*dir 8 sockets audio node.js web-audio-api

我使用以下代码从 Node.js 的套接字解​​码音频块

window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var delayTime = 0;
var init = 0;
var audioStack = [];
var nextTime = 0;

client.on('stream', function(stream, meta){
    stream.on('data', function(data) {
        context.decodeAudioData(data, function(buffer) {
            audioStack.push(buffer);
            if ((init!=0) || (audioStack.length > 10)) { // make sure we put at least 10 chunks in the buffer before starting
                init++;
                scheduleBuffers();
            }
        }, function(err) {
            console.log("err(decodeAudioData): "+err);
        });
    });
});

function scheduleBuffers() {
    while ( audioStack.length) {
        var buffer = audioStack.shift();
        var source    = context.createBufferSource();
        source.buffer = buffer;
        source.connect(context.destination);
        if (nextTime == 0)
            nextTime = context.currentTime + 0.05;  /// add 50ms latency to work well across systems - tune this if you like
        source.start(nextTime);
        nextTime+=source.buffer.duration; // Make the next buffer wait the length of the last buffer before being played
    };
}
Run Code Online (Sandbox Code Playgroud)

但它在音频块之间存在一些我无法弄清楚的间隙/故障。

我还读到,使用 MediaSource 可以执行相同的操作,并由播放器处理计时,而不是手动执行。有人可以提供一个处理 mp3 数据的例子吗?

此外,使用网络音频 API 处理直播的正确方法是什么?我已经阅读了几乎所有关于这个主题的问题,但它们似乎都没有故障。有任何想法吗?

Key*_*ana 4

您可以将此代码作为示例:https ://github.com/kmoskwiak/node-tcp-streaming-server

它基本上使用媒体源扩展。您所需要做的就是从视频更改为音频

buffer = mediaSource.addSourceBuffer('audio/mpeg');