Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript audio.play()当我按下键盘上的另一个键时停止播放_Javascript_Reactjs_Html5 Audio - Fatal编程技术网

Javascript audio.play()当我按下键盘上的另一个键时停止播放

Javascript audio.play()当我按下键盘上的另一个键时停止播放,javascript,reactjs,html5-audio,Javascript,Reactjs,Html5 Audio,我在React上写了一个代码,在每个“按键”事件中播放一个声音。问题是当我按下一个键,在声音结束播放之前,我按下另一个键播放另一个声音。我希望第一个声音将在第二个声音播放的同时播放到结束 每当父组件中的“note”道具发生变化时,useffect将执行并播放相关声音 这是我的密码: function Drums({ note, kit, setNote }) { const audioRef = useRef({}); useEffect(() => { console.

我在React上写了一个代码,在每个“按键”事件中播放一个声音。问题是当我按下一个键,在声音结束播放之前,我按下另一个键播放另一个声音。我希望第一个声音将在第二个声音播放的同时播放到结束

每当父组件中的“note”道具发生变化时,useffect将执行并播放相关声音

这是我的密码:

function Drums({ note, kit, setNote }) {
  const audioRef = useRef({});

  useEffect(() => {
    console.log("Kit: ", kit);
  }, [kit]);

  useEffect(() => {
    if (!audioRef.current[note]) return;
    audioRef.current[note].currentTime = 0;
    const playPromise = audioRef.current[note].play();
    if (playPromise !== undefined) {
      playPromise
        .then(_ => {
          console.log("audio played auto");
          setNote("resetNote");
        })
        .catch(error => {
          console.log("playback prevented");
        });
    }
  }, [note]);

  return (
    <div className='drums-container'>
      <div>{note}</div>
      {Object.keys(drumKits[kit]).map(pad => (
        <audio
          className='drums-container__pad'
          src={drumKits[kit][note]}
          key-data={pad}
          ref={ref => (audioRef.current[pad] = ref)}
        >
          {note}
        </audio>
      ))}
    </div>
  );
}
功能鼓({note,kit,setNote}){
const audioRef=useRef({});
useffect(()=>{
控制台日志(“工具包:”,工具包);
},[工具包];
useffect(()=>{
如果(!audioRef.current[注])返回;
audioRef.current[注].currentTime=0;
const playPromise=audioRef.current[note].play();
如果(playPromise!==未定义){
戏言
.然后(=>{
console.log(“自动播放音频”);
设置注释(“重置注释”);
})
.catch(错误=>{
console.log(“阻止播放”);
});
}
},[注];
返回(
{注}
{Object.keys(drumKits[kit]).map(pad=>(
(音频参考电流[pad]=ref)}
>
{注}
))}
);
}