我正在尝试使用 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/