【发布时间】:2021-02-16 04:04:54
【问题描述】:
我正在尝试使用库https://github.com/AnthumChris/opus-stream-decoder/
我有一个来自高质量麦克风的 OPUS 编码声音流(2ch,48kHz)(但我在它上面循环播放音乐来测试这个)。我知道它有效,因为如果我使用,我可以听到它:
websocat --binary ws://third-i.local/api/sound - | mpv -
(它正在打开 websocket 并将其输出流式传输到 mpv (mplayer))。
但是当我在浏览器中播放时,我听到的只是每秒钟左右声音的一小部分。但是声音本身听起来不错(我相信它只是音乐的一小部分)。
这是我写的在浏览器中监听的JS代码:
let audioWorker: any;
let exampleSocket;
let opusDecoder: any;
let audioCtx: any;
let startTime = 0;
let counter = 0;
function startAudio() {
/*
const host = document.location.hostname;
const scheme = document.location.protocol.startsWith("https") ? "wss" : "ws";
const uri = `${scheme}://${host}/api/sound`;
*/
const uri = "ws://third-i.local/api/sound";
audioCtx = new AudioContext();
startTime = 100 / 1000;
exampleSocket = new WebSocket(uri);
exampleSocket.binaryType = "arraybuffer";
opusDecoder = new OpusStreamDecoder({onDecode});
exampleSocket.onmessage = (event) => opusDecoder.ready.then(
() => opusDecoder.decode(new Uint8Array(event.data))
);
exampleSocket.onclose = () => console.log("socket is closed!!");
}
function onDecode({left, right, samplesDecoded, sampleRate}: any) {
const source = audioCtx.createBufferSource();
const buffer = audioCtx.createBuffer(2, samplesDecoded, sampleRate);
buffer.copyToChannel(left, 0);
buffer.copyToChannel(right, 1);
source.buffer = buffer;
source.connect(audioCtx.destination);
source.start(startTime);
startTime += buffer.duration;
}
https://github.com/BigBoySystems/third-i-frontend/blob/play-audio/src/App.tsx#L54-L88
【问题讨论】:
-
为什么选择 ArrayBuffer?将流作为流处理不是更好吗?您是否尝试将 binaryType 设置为 blob 并用作 ReadableStream?
-
我不知道你如何将 blob 转换为 uint8array。因为
opus-stream-decoder要求您传递一个 uint8array。可以展示一下吗? -
我将 startTime 增加到 10 秒,它可以工作。你知道如何使这个缓冲区动态吗? 1 秒就好了
标签: javascript websocket opus