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文件。 Here is a demo。
这是另一个great resource。
我也正在寻找如何做到这一点的教程。 – ericso 2012-08-24 01:07:28