WΔ_
WΔ_

Reputation: 1259

Why isn't clicking on an audio track immediately triggering play?

I have a StackBlitz minimum code example which illustrates the problem. For brevity, I've also placed the problematic code below.

Whenever the user clicks on a track of a number of tracks, I want the Audio component to immediately play that track, think Spotify etc.

Currently, the source of the audio component is updating, but it does not play the track unless there is a triple click.

I'm not sure why a triple click is needed to create a successful play call.


const changeSource = newSource => {
    setSource(newSource);
    togglePlayPause();
  };

Here is the setSource hook, which is initialised to a default track:

const [source, setSource] = useState(
    'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3'
  );
  const togglePlayPause = () => {
    const prevValue = isPlaying;
    setIsPlaying(!prevValue);
    if (!prevValue) {
      audioPlayer.current.play();
    } else {
      audioPlayer.current.pause();
    }
  };

Upvotes: 0

Views: 86

Answers (1)

Steve -Cutter- Blades
Steve -Cutter- Blades

Reputation: 5432

It'll do that, unless you preload your audio data. The <audio> element would need to go out, bring the data into the browser, process it, then begin to play. There is a way to try to preload the data. By setting <audio preload="auto"> it will "attempt" to preload tracks on page load. But, when dynamically setting source, you can't really get that data until you know what the source is. You can get around this, a little, by using the autoplay attribute, which will cause the browser to automatically begin fetching the source once it is set. (But then, it will also start playing it right away as well.)

Upvotes: 1

Related Questions