Skip to content

How to handle multiple plays of the same sound #88

@lucas-rudd

Description

@lucas-rudd

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}
      ...
   }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions