2

这是我想要做的:

  1. 将麦克风音频发送到 AudioWorketProcessor (works)
  2. 使用 WebSockets 将结果从 AudioWorkletProcessor 发送到服务器(有效)
  3. 通过 WebSockets 接收数据(工作)
  4. 将数据发送到计算机的扬声器(怎么做?)

一切正常,除了我不知道如何实现#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?
  }

任何指导将不胜感激。

4

1 回答 1

2

好的,我相信我可以回答我的问题。这并不强大,但它提供了我需要知道的内容。

  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?
     let fArr = new Float32Array(evt.data);
     let.buf = audioContext.createBuffer(1, 128, 8000);
     buf.copyToChannel(fArr, 0);
     let player = audioContext.createBufferSource();
     player.buffer = buf;
     player.connect(audioContext.destination);    
     player.start(0);
  }
于 2020-06-09T14:05:53.043 回答