【问题标题】:Recorderjs: Buffer is always emptyRecorderjs:缓冲区始终为空
【发布时间】:2013-12-06 00:12:16
【问题描述】:

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

【问题讨论】:

标签: javascript audio buffer html5-audio recorder


【解决方案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 对象,然后是“已进入进程”。您的数组不会为空,并且页面上应该会出现一个播放器,让您可以收听录音。

但是,如果在“Initializing”之前在控制台中打印“Entered process”(意味着您没有足够快地允许使用麦克风),您将返回两个空数组。请注意,console.log(recorder) 现在返回 'undefined' 而不是 Recorder 对象。

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

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

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

【讨论】:

  • 为了让他的生活更轻松,我建议增加调用 process 函数的行中的超时时间:setTimeout(process, 1500); 以便他有更多时间做出反应。如果他不够快,recorder 将是未定义的。
  • i.imgur.com/8L7LyUb.png 我按照你写的做所有事情,但由于某种原因我仍然得到空缓冲区。我的代码看起来像 pastebin.com/xPC8rHJ6
  • 您可以进入recorder.js 并在第 22 行进行这些更改吗? this.node.onaudioprocess = function(e){ console.log('here'); /* Add this */ if (!recording) return; console.log('good!); /* This too */ worker.postMessage({ 让我知道你看到了什么结果。每次处理音频时,您应该会看到成对的“here”和“good”。当然,您确实连接了麦克风,对吗?
  • 这是我当前的代码:pastebin.com/ynVE5E4y,我做了你所说的更改,但由于某种原因我没有到达这里或没有好..是的,我连接了麦克风,当我打开页面时听到自己的声音
  • 提供的示例对您有用吗?如果您使用提供的记录和停止按钮而不是 process,会发生什么情况?我现在的猜测是 onaudioprocess 事件处理程序没有触发,但我不确定为什么。
猜你喜欢
  • 2015-02-27
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多