leoasis / react-sound

Sound component to play audio in your web apps
ISC License
491 stars 80 forks source link

How to handle multiple plays of the same sound #88

Open lucas-rudd opened 4 years ago

lucas-rudd commented 4 years ago

I have an application where the user may take an action in which a sound effect plays.

The user may take this action many times, leading to the sound effect being played multiple times before the prior sound effect has finished.

To accomplish this, I'm pushing all the Sound Components into an array, putting them onto the component state, and attempting to remove them from the state in the onFinishedPlaying so that they get removed from the DOM.

However, since removing them from the array updates the state, the sounds play again.

So, if I the user pressed a key 10 times, the sounds play fine the inital ten times, but then, they play 9 times, then 8 times, then 7 times, then 6 times, etc. as they are all updating the state to remove themselves from the DOM.

What's the suggested way to go about doing this?

This is analogous to what I have in my code in an attempt to accomplish this


onUserAction = () => {
   sounds.push(
          <Sound
            url={SFX}
            playStatus={MusicState.PLAYING}
            loop={false}
            onFinishedPlaying={() => {
              const [
                _,
                ...newSoundComponents
              ] = this.state.SoundComponents;
              this.setState({
                soundComponents: newSoundComponents,
                isSFXPlaying: sounds.length !== 0
              });
            }}
   );
}
this.setState({
  soundComponents: newSoundComponents,
   isSFXPlaying: sounds.length !== 0
}

render() {
   return {
      ...
      {this.state.isSFXPlaying && this.state.soundComponents}
      ...
   }
}