如何将音频上下文中的当前时间链接到输入type = range?

问题描述

我正在使用React.js和网络音频API创建一个播放音乐的应用程序。
Demo

能否请您告诉我如何将输入type = range链接到正在播放的音乐?
通过移动输入type = range,我想更改正在播放音乐的当前时间。


源代码如下。

let audioCtx,audioBuffer,source;
const audioURL = "/piano.mp3";

const App = () => {
  const [load,setLoad] = useState(true);
  const [playing,setPlaying] = useState(false);
  const [total,setTotal] = useState(0);
  const [current,setCurrent] = useState(0);

  const audioLoad = async () => {
    const response = await fetch(audioURL);
    const arrayBuffer = await response.arrayBuffer();
    if (arrayBuffer) {
      audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
      setTotal(audioBuffer.duration);
    }
    setLoad(false);
  };
  useEffect(() => {
    audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    audioLoad();
    return () => {
      audioCtx.close();
      audioCtx = null;
    };
  },[]);

  const playAudio = () => {
    if (!playing) {
      source = audioCtx.createBufferSource();
      source.buffer = audioBuffer;
      source.connect(audioCtx.destination);
      source.start();
      setPlaying(true);
      return;
    }
    source.stop();
    setCurrent(0);
    setPlaying(false);
  };

  const changeSeek = (e) => {
    setCurrent(e.target.value);
    audioCtx.currentTime = current;
    console.log(audioCtx.currentTime);
  };

  return (
    <>
      <p>Total time {total}</p>
      <p>Current time {current}</p>
      <button onClick={playAudio} disabled={load ? true : false}>
        {playing ? "stop" : "play"}
      </button>
      <input
        onChange={changeSeek}
        value={current}
        type="range"
        max={total}
        style={inputStyle}
      />
    </>
  );
};

音频上下文具有currentTime属性,我认为可以通过将input type = range的值分配给该属性来更改音乐的当前时间,但是我无法做到这一点。

此外,我不知道如何自动移动输入type = range以匹配音乐的当前时间。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)