13

最近几天,我尝试使用javascript来录制音频流。我发现没有有效的示例代码。

有浏览器支持吗?

这是我的代码

navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia || navigator.msGetUserMedia; 

navigator.getUserMedia({ audio: true }, gotStream, null);
function gotStream(stream) {

        msgStream = stream;        
        msgStreamRecorder = stream.record(); // no method record :(
}
4

5 回答 5

33

getUserMedia 使您可以访问设备,但录制音频取决于您。为此,您需要“监听”设备,构建数据缓冲区。然后,当您停止收听设备时,您可以将该数据格式化为 WAV 文件(或任何其他格式)。格式化后,您可以将其上传到您的服务器 S3,或直接在浏览器中播放。

要以对构建缓冲区有用的方式收听数据,您将需要一个 ScriptProcessorNode。ScriptProcessorNode 基本上位于输入(麦克风)和输出(扬声器)之间,让您有机会在音频数据流式传输时对其进行操作。不幸的是,实现并不简单。

你需要:

  • getUserMedia访问设备
  • AudioContext创建一个 MediaStreamAudioSourceNode 和一个 ScriptProcessorNode
  • MediaStreamAudioSourceNode 表示音频流
  • ScriptProcessorNode通过 onaudioprocessevent 访问流式音频数据。该事件公开了您将用来构建缓冲区的通道数据。

把它们放在一起:

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 文件。 这是一个演示

这是另一个很棒的资源

于 2013-10-08T02:34:45.830 回答
7

对于支持MediaRecorder API的浏览器,请使用它。

对于不支持 MediaRecorder API 的旧浏览器,有三种方法可以做到

  1. 作为wav
  2. 作为mp3
  3. as opus packets (可以得到输出为wav,mp3ogg
于 2015-03-25T05:00:28.440 回答
2

你可以查看这个网站: https ://webaudiodemos.appspot.com/AudioRecorder/index.html

它将音频存储到客户端的文件 (.wav) 中。

于 2013-08-22T06:58:00.647 回答
1

有一个错误,目前只允许音频。请参阅http://code.google.com/p/chromium/issues/detail?id=112367

于 2012-08-30T08:46:16.667 回答
-2

目前,如果不将数据发送到服务器端,这是不可能的。但是,如果他们开始支持MediaRecorder 工作草案,这将很快在浏览器中成为可能。

于 2013-03-16T17:53:31.900 回答