这是我想要做的:
- 将麦克风音频发送到 AudioWorketProcessor (works)
- 使用 WebSockets 将结果从 AudioWorkletProcessor 发送到服务器(有效)
- 通过 WebSockets 接收数据(工作)
- 将数据发送到计算机的扬声器(怎么做?)
一切正常,除了我不知道如何实现#4。这就是我所拥有的,简化了一些事情以专注于问题:
//1. 设置音频上下文的代码。将麦克风连接到工作集
const audioContext = new AudioContext({ sampleRate: 8000 });
audioContext.audioWorklet.addModule('/common/recorderworkletprocess.js').then(
function () {
const recorder = new AudioWorkletNode(audioContext, 'recorder-worklet');
let constraints = { audio: true };
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
const microphone = audioContext.createMediaStreamSource(stream);
microphone.connect(recorder);
recorder.connect(audioContext.destination);
});
}
);
//2。AudioWorklet 处理器。将音频发送到 WebSocket,WebSocket 将其以二进制形式发送到服务器:
class RecorderWorkletProcessor extends AudioWorkletProcessor {
constructor() {
super();
}
process(inputs) {
const inputChannel = inputs[0][0]; //inputChannel Float32Array(128)
socket.send(inputChannel); // sent as byte[512]
return true;
}
}
registerProcessor('recorder-worklet', RecorderWorkletProcessor);
//3 和 4. 最后,服务器完全按照收到的数据发回。WebSocket 将其转换为 ArrayBuffer(512)。在这里,我想尽一切努力将其作为音频输出到计算机的扬声器:
socket.messageReceived = function (evt) {
// evt.data contains an ArrayBuffer with length of 512
// I want this to be played on the computer's speakers. How to do this?
}
任何指导将不胜感激。