使用 createMediaElementSource 节点播放音乐需要做什么?

What do I need to do to play music using createMediaElementSourceNode?

我正在尝试连接 MediaElementAudioSourceNodegainNode 以更改 mp3 文件的音量。
CodeSandBox
该代码是参考以下页面创建的。
AudioContext.createMediaElementSource() - Web APIs | MDN

但是音乐不会播放。
我的代码中缺少什么?

下面是源代码。


let audio, gainNode;

const App = () => {
  const [playing, setPlaying] = useState(false);
  useEffect(() => {
    const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    audio = new Audio("/piano.mp3");
    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>
    </>
  );
};

去掉useEffect中的以下代码即可播放音频

const sourceNode = audioCtx.createMediaElementSource(audio);
sourceNode.connect(gainNode);
audio.crossOrigin = "anonymous";

感谢 Kaiido。