mukul
mukul

Reputation: 181

How to autoplay next song without button interaction

In my audio player, i load a song by default and then hit play button to play the audio. Now when i hit the next song button, it loads the next song but does not play it. I Have to again hit pause/play button to play it. Same thing with playing next song when previous song has ended. So, the player requires interaction to play the song after its loaded. How can i autoplay next (or previous) songs without having to interact with the player each time?

exports.songsdata = [
    {
        "title": "song1",
        "url": "https://song1.mp3"
    },
    {
        "title": "song2",
        "url": "https://song2.mp3"
    },
    {
        "title": "song3",
        "url": "https://song3.mp3"
    }
]

const [currentSong, setCurrentSong] = useState(songsdata[0]);
const playNext = () => {
    const index = songs.findIndex(x=>x.title == currentSong.title);

    if (index == songs.length-1)
    {
      setCurrentSong(songs[0]);
    }
    else
    {
      setCurrentSong(songs[index + 1]);
    }
}

<div className="AudioPlayer">
    <audio src={currentSong.url} />
</div>

<div className="controls">
    <Button className='btn_action' onClick={playNext} />
</div>

Upvotes: 1

Views: 1724

Answers (3)

Tamas Szoke
Tamas Szoke

Reputation: 5542

The canplay event could be used to play the audio after it's loaded. So after this event called, you can call audio.play() to play the audio.

Canplay event: The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.

There's also the canplaythrough event which is called after the audio is fully loaded.

For the autoplay feature, listen for the ended event of the audio tag and call the playNext() function from that.

Ended event: Playback has stopped because the end of the media was reached.

Example

const canplayEvent = () => {
  audio.play()
}

const endedEvent = () => {
  playNext()
}

<div className="AudioPlayer">
  <audio src={currentSong.url} onCanplay={canplayEvent} onEnded={endedEvent}/>
</div>

More information

Upvotes: 1

Evans Kiptarus Kibet
Evans Kiptarus Kibet

Reputation: 194

canplay is a trick here.

const video = document.querySelector('video');

video.addEventListener('canplay', (event) => {
  console.log('Video can start, but not sure it will play through.');
});

Upvotes: 0

Sivarajan Sivanesan
Sivarajan Sivanesan

Reputation: 172

audio tag can add event ended. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio#events

add a event listener to the audio and once it is ended you can call playNext()

Upvotes: 0

Related Questions