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

时间:2017-12-01 19:43:47

标签: node.js sockets audio web-audio-api

我使用以下代码解码来自nodejs&socket的音频块

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
    };
}

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

我还读到,使用MediaSource可以做同样的事情并让玩家处理时间而不是手动操作。有人可以提供处理mp3数据的例子吗?

此外,这是使用网络音频API处理实时流媒体的正确方法吗?我已经阅读了关于这个主题的几乎所有问题,但似乎没有任何问题没有毛刺。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

是@Keyne是正确的

const mediaSource = new MediaSource()
const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg')
player.src = URL.createObjectURL(mediaSource)
sourceBuffer.appendBuffer(chunk) // Repeat this for each chunk as ArrayBuffer
player.play()

但是只有在您不关心IOS支持(https://developer.mozilla.org/en-US/docs/Web/API/MediaSource#Browser_compatibility)时才这样做

否则,请让我知道您的操作方式!