Home > Net >  How to autoplay next song without button interaction
How to autoplay next song without button interaction

Time:07-30

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>

CodePudding user response:

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

CodePudding user response:

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()

CodePudding user response:

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.');
});
  • Related