getUserMedia 使您可以访问设备,但录制音频取决于您。为此,您需要“监听”设备,构建数据缓冲区。然后,当您停止收听设备时,您可以将该数据格式化为 WAV 文件(或任何其他格式)。格式化后,您可以将其上传到您的服务器 S3,或直接在浏览器中播放。
要以对构建缓冲区有用的方式收听数据,您将需要一个 ScriptProcessorNode。ScriptProcessorNode 基本上位于输入(麦克风)和输出(扬声器)之间,让您有机会在音频数据流式传输时对其进行操作。不幸的是,实现并不简单。
你需要:
把它们放在一起:
navigator.getUserMedia({audio: true},
function(stream) {
// create the MediaStreamAudioSourceNode
var context = new AudioContext();
var source = context.createMediaStreamSource(stream);
var recLength = 0,
recBuffersL = [],
recBuffersR = [];
// create a ScriptProcessorNode
if(!context.createScriptProcessor){
node = context.createJavaScriptNode(4096, 2, 2);
} else {
node = context.createScriptProcessor(4096, 2, 2);
}
// listen to the audio data, and record into the buffer
node.onaudioprocess = function(e){
recBuffersL.push(e.inputBuffer.getChannelData(0));
recBuffersR.push(e.inputBuffer.getChannelData(1));
recLength += e.inputBuffer.getChannelData(0).length;
}
// connect the ScriptProcessorNode with the input audio
source.connect(node);
// if the ScriptProcessorNode is not connected to an output the "onaudioprocess" event is not triggered in chrome
node.connect(context.destination);
},
function(e) {
// do something about errors
});
我建议您使用AudioRecorder代码,而不是自己构建所有这些,这太棒了。它还处理将缓冲区写入 WAV 文件。 这是一个演示。
这是另一个很棒的资源。