如何导出网络音频流的最后3秒数据



问题:我正在使用网络音频API。我需要缓冲一个不间断的音频流,就像一个无线电流。当我收到通知时,我需要获取过去3秒的音频数据并将其发送到服务器。我怎样才能做到这一点?nodejs有一个内置的缓冲区,但它似乎不是一个循环缓冲区,如果我在其中写入一个不间断的流,它似乎会溢出。

帮助您理解我的问题的背景:我正在实现一种基于环境音频的web身份验证方法。简单地说,我需要比较两条音频信号(一条来自客户端,另一条来自锚设备,它们都与服务器同步),如果它们足够相似,则服务器会批准身份验证请求。使用web audio API在客户端和锚设备上实现音频录制。

我需要在锚设备上管理一个缓冲区来流式传输环境音频。锚设备应该一直在运行,所以流不会结束。

您可以使用ScriptProcessorNode从流中捕获音频。虽然这是不赞成的,但到目前为止,没有任何浏览器真正实现新的AudioWorker。

var N = 1024;
var time = 3; // Desired time of capture;
var frame_holder = [];
var time_per_frame = N / context.sampleRate;
var num_frames = Math.ceil(time / time_per_frame); // Minimum number to meet time
var script = context.createScriptProcessor(N,1,1);
script.connect(context.destination);
script.onaudioprocess = function(e) {
var input = e.inputBuffer.getChannelData(0);
var output = e.outputBuffer.getChannelData(0);
var copy = new Float32Array(input.length);
for (var n=0; n<input.length; n++) {
output[n] = 0.0; // Null this as I guess you are capturing microphone
copy[n] = input[n];
}
// Now we need to see if we have more than 3s worth of frames
if (frame_holder.length > num_frames) {
frame_holder = frame_holder.slice(frame_holder.length-num_frames);
}
// Add in the current frame
var temp = frame_holder.slice(1); // Cut off first frame;
frame_holder = temp.concat([copy]); // Add the latest frame
}

然后,对于实际传输,您只需要将复制的帧串在一起。这比试图保持一个长数组更容易,当然这也是可能的。

最新更新