Web Audio API将单声道拆分为立体声

时间:2019-03-04 15:09:13

标签: javascript web-audio-api

可以说我有一个连接到目标节点的源节点。 即使音频是单声道,我也希望能够独立地控制每只耳朵的音量,就像在使用带有分离器和合并节点的立体声音频时所做的那样。

已经尝试在单声道源节点上使用拆分器和合并节点,但是正确的通道显示为空。

立体声示例:

var audioCtx = new AudioContext();
var source = audioCtx.createMediaElementSource(myAudio);
var gainNodeL = audioCtx.createGain();
var gainNodeR = audioCtx.createGain();
var splitter = audioCtx.createChannelSplitter(2);
var merger = audioCtx.createChannelMerger(2);

source.connect(splitter);
splitter.connect(gainNodeL, 0);
splitter.connect(gainNodeR, 1);

gainNodeL.connect(merger, 0, 0);
gainNodeR.connect(merger, 0, 1);

merger.connect(audioCtx.createMediaStreamDestination());

当我用单声道音频执行此操作时,右声道变成空的。

1 个答案:

答案 0 :(得分:0)

如果信号只是单声道的(换句话说,其channelCount为1),则不需要ChannelSplitterNode。我对示例进行了一些修改。现在,它确实可以分割振荡器的单声道信号。

var audioCtx = new AudioContext();
var oscillator = audioCtx.createOscillator();
var gainNodeL = audioCtx.createGain();
var gainNodeR = audioCtx.createGain();
var merger = audioCtx.createChannelMerger(2);

oscillator.connect(gainNodeL);
oscillator.connect(gainNodeR);

gainNodeL.connect(merger, 0, 0);
gainNodeR.connect(merger, 0, 1);

merger.connect(audioCtx.destination);

oscillator.start();

function left () {
    gainNodeL.gain.value = 1;
    gainNodeR.gain.value = 0;
}

function right () {
    gainNodeL.gain.value = 0;
    gainNodeR.gain.value = 1;
}

function center () {
    gainNodeL.gain.value = 1;
    gainNodeR.gain.value = 1;
}