简体   繁体   中英

How to stop a previous call from a new instance of an imported function inside a useEffect hook in react

I was trying to pause/play and change instruments in the code below by trying to call the function responsible in a useEffect Hook. The playKeyboard method uses a new instance every time it is called, but instead, I want that state to be stopped and merged completely.

 useEffect(() => {
    if (keyboard.length > 0)
      playKeyboard(keyboard, stat.pause, stat.index, stat.selectSound);
  }, [keyboard, stat]);

  const onInstrumentChange = (event) => {
    const newStat = { ...stat, selectSound: { value: event.target.value } };
    setStat(newStat);
  };

The function responsible for creating the sound is partially:

async function playKeyboard(keyboardArray, pause, index, selectSound) {
 var __audioSynth = new AudioSynth();
 __audioSynth.setVolume(0.08);
 var __octave = 4; //sets position of middle C, normally the 4th octave

 //to select the instrument to play
 // let selectSound = {
 //   value: "1"
 //   //"0" //piano
 //   // "1" //organ
 //   // "2" //acoustic
 //   // "3" //edm
 // };

 // Generates audio for pressed note and returns that to be played
 var fnPlayNote = function(note, octave, duration) {
   var src = __audioSynth.generate(selectSound.value, note, octave, duration);
   var container = new Audio(src);
   container.addEventListener("ended", function() {
     container = null;
   });
   container.addEventListener("loadeddata", function(e) {
     e.target.play();
   });

Is there a recommended way to stop the previously registered or called function. FullCode in CodeSandbox is: here for the keyboard method and here for the react component that uses it

I guess what you are trying to achieve can be done using, useEffect with Cleanup, in every useEffect you can return a function that will be called with the component exits,

useEffect(() => {
   if (keyboard.length > 0){
     playKeyboard(keyboard, stat.pause, stat.index, stat.selectSound);
     return stopKeyboard(arguments); // Implement the sound stop functionality here
   }
 }, [keyboard, stat]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM