首页 > 解决方案 > 如何从 Three.JS AudioContext 将音频连接到 MediaStream

问题描述

我正在从画布中实例化 MediaStream。我需要将来自 Three.js 的音频流中的音频连接到该流。

我尝试了很多东西,但最简洁的是提供的代码。是否添加了流但音频只是听不见?

const context: AudioContext = ThreeAudioContext.getContext();
const destination = context.createMediaStreamDestination();
const source = context.createMediaStreamSource(destination.stream);
source.connect(destination);
stream.addTrack(destination.stream.getAudioTracks()[0]);

我也试过这个,看看是否连接了音频,但我仍然听不到任何声音。

const context: AudioContext = ThreeAudioContext.getContext();
const destination = context.createMediaStreamDestination();
const source = context.createMediaStreamSource(destination.stream);

const gainNode = context.createGain();
gainNode.gain.value = 1;

source.connect(gainNode);
gainNode.connect(destination);
stream.addTrack(destination.stream.getAudioTracks()[0]);

我想听 Three.JS 的音频,但我什么也没听到。我在游戏中可以调节音量。这会影响事情吗?我应该注意我首先调用 canvas.captureStream(),然后执行这个“轨道添加”,然后实例化一个记录器。

标签: javascriptthree.jsweb-audio-api

解决方案


对于未来的开发者:

const context: AudioContext = ThreeAudioContext.getContext();
const destination = context.createMediaStreamDestination();
this.audioListener.getInput().connect(destination);
this.backgroundGainNode.connect(destination);
stream.addTrack(destination.stream.getAudioTracks()[0]);

简而言之,要将音频连接到 MediaRecorder,请调用 createMediaStreamDestination 并将 gainNode(音量节点)连接到新创建的目的地。然后,将轨道添加到流中。

我遇到了几个小问题: - 您连接的所有增益节点都需要位于相同的音频上下文中。- 如果你想将音频连接到流,即使它可能听不到,你需要创建一个独立的 GainNode。

当然,我说 GainNode 是因为你可能会使用不同类型的 AudioNode,但我假设 95% 的人只想播放音频,除了音量之外没有任何改变。


推荐阅读