簡體   English   中英

如何使用網絡音頻 api 獲取原始 pcm 音頻?

[英]How to use web audio api to get raw pcm audio?

usergetmedia 如何在 chrome 中使用麥克風然后流式傳輸以獲取原始音頻? 我需要獲得線性 16 的音頻。

我發現的唯一兩個清晰且有意義的例子如下:

AWS 實驗室: 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”選項會對錄音產生負面影響。

它們都是極好的資源,您一定能夠解決您的問題。

不幸的是,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 : //stackoverflow.com/a/7870190/362536

您應該查看MediaDevices.getUserMedia() API 的MediaTrackConstraints.sampleSize屬性。 使用sampleSize約束,如果您的音頻硬件允許,您可以將樣本大小設置為 16 位。

就實施而言,這就是鏈接和谷歌的用途......

這是一些 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>

注意 - 在瀏覽器中運行之前,首先調低音量,因為代碼既會收聽您的麥克風,又會向揚聲器發送實時輸出,因此您會很自然地聽到反饋 --- 就像 Jimmy Hendrix 的反饋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM