是否可以使用Web Auido API在不失真声音的情况下向MediaElementAudioSourceNode添加效



我正试图通过连接MediaElementAudioSourceNode和GainNode来操作卷
下面是它的演示。
CodeSandBoxs

如果按下"播放"按钮,音乐将正常播放
但是,操纵input type=range来更改音量会使您播放的声音失真。(如果你试着的话,把音量调低。(

有没有办法在不失真声音的情况下改变音量
如果使用MediaElementAudioSourceNode,这是不可避免的事情吗
我找了一篇提到声音失真现象的文章,但找不到。

在演示中,我们只想改变音量,但我们也想添加混响、延迟等。


演示代码如下。

let audio, gainNode;
const App = () => {
const [playing, setPlaying] = useState(false);
useEffect(() => {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
audio = new Audio("/piano.mp3");
audio.crossOrigin = "anonymous"
const sourceNode = audioCtx.createMediaElementSource(audio);
gainNode = audioCtx.createGain();
sourceNode.connect(gainNode);
gainNode.connect(audioCtx.destination);
return () => audioCtx.close();
}, []);
const playPause = () => {
if (playing) {
audio.pause();
setPlaying(false);
return;
}
audio.play();
setPlaying(true);
};
const cahngeVolume = (e) => (gainNode.gain.value = e.target.value);
return (
<>
<button onClick={playPause} style={{ display: "block" }}>
{playing ? "Pause" : "Play"}
</button>
<div>
<span>Volume</span>
<input type="range" onChange={cahngeVolume} step="any" />
</div>
</>
);
};

失真的原因可能是GainNode的范围并没有真正映射到输入的范围。默认情况下,范围输入的最小/最大值为0和100。然而,CCD_ 3确实将信号与其增益值相乘。这意味着滑块的最大值最好为1。

<input type="range" onChange={cahngeVolume} step="any" max="1" />

这样,滑块从0(无声音(变为1(无放大(。

最新更新