如何使用Web Audio API获取原始PCM音频?

14

如何在谷歌浏览器中使用usergetmedia并流式传输原始音频?我需要以线性16的格式获取音频。


我发现它与scriptprocessornode有关。 - jeo.e
5个回答

10
我找到的两个清晰明了且有意义的示例如下:
AWS Labs: https://github.com/awslabs/aws-lex-browser-audio-capture/blob/master/lib/worker.js 这个AWS资源非常好。它向你展示如何将录制的音频导出为“作为PCM编码的WAV格式”。Amazon Lex是AWS提供的一项转录服务,要求音频以PCM编码并包装在WAV容器中。你可以简单地调整代码以使其适用于你的需求!AWS还具有一些其他功能,例如“降采样”,可以在不影响录音的情况下更改采样率。
RecordRTC: https://github.com/muaz-khan/RecordRTC/blob/master/simple-demos/raw-pcm.html RecordRTC是一个完整的库。你可以再次调整他们的代码或找到编码音频为原始PCM的代码片段。你也可以实现他们的库并直接使用代码。使用此库的音频配置选项中的“desiredSampleRate”会对录音产生负面影响。
它们都是很好的资源,你肯定能解决你的问题。

2
这里列出了一些支持WebAudioAPI到Raw PCM音频的库:https://dev59.com/UFYN5IYBdhLWcg3whIXz#57837816 - Venryx
@Venryx非常有用的stackoverflow链接^^ - imbatman

9

很遗憾,MediaRecorder不支持原始PCM捕获。(在我看来是一个悲伤的疏忽。) 因此,您需要自己获取原始样本并进行缓冲/保存。

您可以使用ScriptProcessorNode来完成这个任务。通常,该节点用于以编程方式修改音频数据,以获得自定义效果等。但是,您完全可以将其用作捕获点。尚未经过测试,但请尝试以下代码:

const captureNode = audioContext.createScriptProcessor(8192, 1, 1);
captureNode.addEventListener('audioprocess', (e) => {
  const rawLeftChannelData = inputBuffer.getChannelData(0);
  // rawLeftChannelData is now a typed array with floating point samples
});

您可以在MDN上找到一个更完整的示例。

这些浮点数样本以零0为中心,理想情况下将绑定到-11。在转换为整数范围时,您需要将值夹紧到此范围,并裁剪超出此范围的任何内容。(如果在浏览器中混合了大声音乐,则值有时可能超过-11。理论上,浏览器还可以从外部声音设备记录float32样本,这些样本可能超出该范围,但我不知道有哪个浏览器/平台会这样做。)

在转换为整数时,值是有符号还是无符号很重要。如果是有符号的,对于16位,范围是-3276832767。对于无符号的,它是065535。确定您要使用的格式,并将-11的值缩放到该范围。

这个转换还有一个需要注意的地方... 字节序可能很重要。参见:https://dev59.com/YGsz5IYBdhLWcg3wfnwx#7870190

1
在此转换完成后,是否有任何方法可以将其转回音频媒体流并在音频标签中播放? - Gaurav Aggarwal

0

这里有一些Web Audio API,它使用麦克风捕获和播放原始音频(在运行此页面之前请将音量调低)...要查看PCM格式的原始音频片段,请查看浏览器控制台...为了好玩,它还将这个PCM发送到FFT调用中,以获取音频曲线的频域和时域

<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>capture microphone then show time & frequency domain output</title>
 
<script type="text/javascript">

var webaudio_tooling_obj = function () {

    var audioContext = new AudioContext();

    console.log("audio is starting up ...");

    var BUFF_SIZE_RENDERER = 16384;
    var SIZE_SHOW = 3; // number of array elements to show in console output

    var audioInput = null,
    microphone_stream = null,
    gain_node = null,
    script_processor_node = null,
    script_processor_analysis_node = null,
    analyser_node = null;

    if (!navigator.getUserMedia)
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia || navigator.msGetUserMedia;

    if (navigator.getUserMedia){

        navigator.getUserMedia({audio:true}, 
            function(stream) {
                start_microphone(stream);
            },
            function(e) {
                alert('Error capturing audio.');
            }
            );

    } else { alert('getUserMedia not supported in this browser.'); }

    // ---

    function show_some_data(given_typed_array, num_row_to_display, label) {

        var size_buffer = given_typed_array.length;
        var index = 0;

        console.log("__________ " + label);

        if (label === "time") {

            for (; index < num_row_to_display && index < size_buffer; index += 1) {

                var curr_value_time = (given_typed_array[index] / 128) - 1.0;

                console.log(curr_value_time);
            }

        } else if (label === "frequency") {

            for (; index < num_row_to_display && index < size_buffer; index += 1) {

                console.log(given_typed_array[index]);
            }

        } else {

            throw new Error("ERROR - must pass time or frequency");
        }
    }

    function process_microphone_buffer(event) {

        var i, N, inp, microphone_output_buffer;

        // not needed for basic feature set
        // microphone_output_buffer = event.inputBuffer.getChannelData(0); // just mono - 1 channel for now
    }

    function start_microphone(stream){

        gain_node = audioContext.createGain();
        gain_node.connect( audioContext.destination );

        microphone_stream = audioContext.createMediaStreamSource(stream);
        microphone_stream.connect(gain_node); 

        script_processor_node = audioContext.createScriptProcessor(BUFF_SIZE_RENDERER, 1, 1);
        script_processor_node.onaudioprocess = process_microphone_buffer;

        microphone_stream.connect(script_processor_node);

        // --- enable volume control for output speakers

        document.getElementById('volume').addEventListener('change', function() {

            var curr_volume = this.value;
            gain_node.gain.value = curr_volume;

            console.log("curr_volume ", curr_volume);
        });

        // --- setup FFT

        script_processor_analysis_node = audioContext.createScriptProcessor(2048, 1, 1);
        script_processor_analysis_node.connect(gain_node);

        analyser_node = audioContext.createAnalyser();
        analyser_node.smoothingTimeConstant = 0;
        analyser_node.fftSize = 2048;

        microphone_stream.connect(analyser_node);

        analyser_node.connect(script_processor_analysis_node);

        var buffer_length = analyser_node.frequencyBinCount;

        var array_freq_domain = new Uint8Array(buffer_length);
        var array_time_domain = new Uint8Array(buffer_length);

        console.log("buffer_length " + buffer_length);

        script_processor_analysis_node.onaudioprocess = function() {

            // get the average for the first channel
            analyser_node.getByteFrequencyData(array_freq_domain);
            analyser_node.getByteTimeDomainData(array_time_domain);

            // draw the spectrogram
            if (microphone_stream.playbackState == microphone_stream.PLAYING_STATE) {

                show_some_data(array_freq_domain, SIZE_SHOW, "frequency");
                show_some_data(array_time_domain, SIZE_SHOW, "time"); // store this to record to aggregate buffer/file
            }
        };
    }

}(); //  webaudio_tooling_obj = function()

</script>

</head>
<body>

    <p>Volume</p>
    <input id="volume" type="range" min="0" max="1" step="0.1" value="0.0"/>

    <p> </p>
    <button onclick="webaudio_tooling_obj()">start audio</button>

</body>
</html>

注意 - 在浏览器中运行上述代码之前,请先将音量调低,因为该代码既会监听您的麦克风,又会实时向扬声器发送输出,因此您自然会听到反馈 --- 就像吉米·亨德里克斯的反馈一样。


我在Chrome 83.0.4103.97中遇到了“AudioContext未被允许启动。它必须在页面上的用户手势之后恢复(或创建)。”的问题。 - asnov
去掉函数后面的“()”,然后添加这个方法对我很有帮助。 - asnov

0

3
欢迎来到StackOverflow。在回答问题时,最好在回答中放入一些相关的示例代码。如果你只是提供一个链接,可以将其作为评论留在问题下面。无论如何,在这个问题中,捕获位深度并不重要,因为Web Audio API总是提供浮点样本。此外,你会发现除了一些特殊的嵌入式硬件之外,几乎所有设备都支持16位音频。 - Brad

0

这个库增加了对音频/pcm的支持。它基本上是一个即插即用的替代品。

https://github.com/streamproc/MediaStreamRecorder

替换类名,然后将 mimetype 添加为 pcm。就像下面这样。

var mediaRecorder = new MediaStreamRecorder(stream);
    mediaRecorder.mimeType = 'audio/pcm';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接