Recorderjs:缓冲区总是空的

Recorderjs: Buffer is always empty

本文关键字:缓冲区 Recorderjs      更新时间:2024-04-04

我正在构建一个简单的语音聊天应用程序。我决定使用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个空数组:(

我稍微更改了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)现在返回"undefined",而不是Recorder对象。

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

编辑:当然,你可以通过增加setTimeout(process, 1500)来给自己更多的时间做出反应。

最后两条注释:
1.确保您使用的是Chrome!
2.我把recorder.stop()recorder.clear()这两行加到了process上。如果没有这些行,您会发现第一次加载页面时录制的音频已准备好进行下一次录制。