javascript - 如何从 AudioContext 获取缓冲区/原始数据?

标签 javascript web html5-audio audiocontext

我正在尝试使用 GetUserMedia() 从用户麦克风录制和保存声音片段和 AudioContext蜜蜂。

我已经能够使用 MediaRecorder 做到这一点API,但不幸的是,Safari/iOS 不支持,所以我想只使用 AudioContext API 和由此而来的缓冲区。

我得到了部分使用this tutorial from Google Web fundamentals的东西,但我不知道如何执行他们建议的以下步骤。

var handleSuccess = function(stream) {
    var context = new AudioContext();
    var source = context.createMediaStreamSource(stream);
    var processor = context.createScriptProcessor(1024, 1, 1);

    source.connect(processor);
    processor.connect(context.destination);

    processor.onaudioprocess = function(e) {
        // ******
        // TUTORIAL SUGGESTS: Do something with the data, i.e Convert this to WAV 
        // ******
        // I ASK: How can I get this data in a buffer and then convert it to WAV etc.??
        // *****
        console.log(e.inputBuffer);
    };
};

navigator.mediaDevices.getUserMedia({ audio: true, video: false })
    .then(handleSuccess);

正如教程所说:

The data that is held in the buffers is the raw data from the microphone and you have a number of options with what you can do with the data:

  • Upload it straight to the server
  • Store it locally
  • Convert to a dedicated file format, such as WAV, and then save it to your servers or locally


我可以做到这一切,但是 停止上下文后,我无法弄清楚如何获取音频缓冲区 .

MediaRecorder你可以这样做:
mediaRecorder.ondataavailable = function(e) {
    chunks.push(e.data);
}

然后当你完成录制时,chunks 中有一个缓冲区。 .正如教程所建议的那样,必须有一种方法,但我找不到 data在第一个代码示例中插入缓冲区。

获得音频缓冲区后,我可以 convert it to WAV并将其制成blob等。

谁能帮我这个? (我不想使用 MediaRecorder API)

最佳答案

e.inputBuffer.getChannelData(0)
其中 0 是第一个 channel 。这应该返回带有原始 PCM 数据的 Float32Array,然后您可以将其转换为 ArrayBuffer e.inputBuffer.getChannelData(0).buffer并发送给将其转换为所需格式的工作人员。
.getChannelData() 文档:https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer/getChannelData .
关于类型化数组:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays , https://javascript.info/arraybuffer-binary-arrays .

关于javascript - 如何从 AudioContext 获取缓冲区/原始数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53589970/

相关文章:

javascript - 如何使用 jQuery.post 将 JSON 数据发送到 php 脚本?

javascript - JQuery - 更改文本中字符串的颜色,忽略 <br> 之间

javascript - 如何从 Service Worker 获取通知

javascript - 在 javascript 中捕获 "' this"

javascript - 如何向动态创建的元素触发事件?

python - 从 python 读取 stdout 生成 XML

javascript - 如何使用 Web Audio API 降低麦克风输入的噪音?

html - 保护从 HTML 5 流式传输的歌曲

javascript - 如何理解 Web Audio API panner 节点的 "distance"方法之间的关系

javascript - 是否有任何预防方法可以删除 `IsTrial` 并轻松破解 WinRT 应用程序?