2

我正在构建一个简单的语音聊天应用程序。我决定使用 NodeJS,但我不明白为什么缓冲区总是空的。

我正在使用https://github.com/mattdiamond/Recorderjs

我的代码如下所示:

var audio_context;
var recorder;

function startUserMedia(stream) {
    var input = audio_context.createMediaStreamSource(stream);    
    input.connect(audio_context.destination);    
    recorder = new Recorder(input);
}

function process() {
 recorder.record();

 setTimeout(function() {
    recorder.getBuffer(function(data) {
        console.log(data);
    });
 }, 3000);
}

window.onload = function init() {
try {
  window.AudioContext = window.AudioContext || window.webkitAudioContext;
  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
  window.URL = window.URL || window.webkitURL;

  audio_context = new AudioContext;
} catch (e) {
    console.log(e);
}

navigator.getUserMedia({audio: true}, startUserMedia);

setTimeout(process, 1500); 
};

问题是当执行 getBuffer 回调时,数据总是包含 2 个空数组:(

4

1 回答 1

1

process我稍微更改了您的代码,以便更容易看到发生了什么。

function process() {
  console.log('Entered process');
  console.log(recorder);
  recorder && recorder.record();

  setTimeout(function() {
    console.log('Trying to get buffer');
    recorder.stop();
    recorder.getBuffer(function(data) {
      console.log(data);
      createDownloadLink();
      recorder.clear();
    });
  }, 3000);
}

我还在开头添加了一行startUserMedia

console.log('Initializing');

当您访问该页面时,Chrome 应该会询问您是否允许使用您的麦克风。如果您允许在控制台中打印“输入的进程”之前使用麦克风,那么一切都应该正常工作。您将看到消息“正在初始化”以及 Recorder 对象,然后是“已进入进程”。您的数组不会为空,并且页面上应该会出现一个播放器,让您可以收听录音。

但是,如果在“初始化”之前在控制台中打印“输入的进程”(意味着您没有足够快地允许使用麦克风),您将返回两个空数组。请注意,console.log(recorder)现在返回“未定义”而不是 Recorder 对象。

该函数startUserMedia是 的回调navigator.getUserMedia函数,该函数告诉浏览器提示用户允许使用所需的媒体设备(在本例中为您的麦克风)。在用户授予权限之前,不会执行回调。该变量recorder在 中初始化startUserMedia,因此我们必须等待用户授予权限才能使用 Recorder 对象的 API。process但是,无论是否获得许可,都会在短暂延迟后尝试录制。这导致了上述竞争条件。

编辑:当然,您可以通过增加setTimeout(process, 1500).

最后两个注意事项:
1. 确保您使用的是 Chrome!
2.我添加了行recorder.stop()recorder.clear()process。如果没有这些行,您会发现第一次加载页面时录制的音频会添加到您的下一次录制中。

于 2013-12-10T05:51:18.060 回答