通过网络流式传输麦克风音频输入(RAW PCM)

时间:2020-09-23 17:52:09

标签: javascript html networking audio html5-audio

仅使用javascript录制原始pcm音频的最佳方法是什么?我将通过网络连接流式传输它,然后需要在另一侧重新组装数据包。联网部分已经完成,但是我似乎无法弄清楚如何录制,然后将原始的pcm数据包放入播放器中,然后让我在扬声器上听到。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

未经测试,但这是我要怎么做

  1. 询问使用麦克风的权限
  2. 使用具有流的回调作为输入,并将其连接到ScriptProcessor
  3. ScriptProcessor为您提供了一系列示例

以下一些代码段可能会有所帮助

// ask for permission
navigator.getUserMedia( {audio:true}, successCB, errorCB );

回调示例

function successCB(stream) {
    const ctx = new AudioContext();
    const mediaStreamSource = ctx.createMediaStreamSource(stream);

    const scriptNode = ctx.createScriptProcessor(4096, 1, 1);
    scriptNode.onaudioprocess(audioProcessingEvent => {
        const inputBuffer = audioProcessingEvent.inputBuffer;
        const inputData = inputBuffer.getChannelData(0 /*channel*/);

        for (var sample = 0; sample < inputBuffer.length; sample++) {
            const THE_SAMPLE = inputData[sample];
            // save it in an array ?
        }
    });
    
    // connect the mic to the script
    mediaStreamSource.connect(scriptNode);

    // if you need to hear yourself (be careful with feedback or use headphones)
    mediaStreamSource.connect( ctx.destination );
}

仅供参考,对于我尚未尝试过的AudioWorkletNode,不推荐使用ScriptProcessor。