Skip to content

JavaScript Audio Object how to play next track on clicking next

I am making a music web app where users can load song or load array of music. I tried to make a button where user can skip the track and play the next track from the array. I tried in my own method and it actually working quiet well.

heres my music object:

    getNextSong()
    {
        if(this.songArray && this.i > -1 && this.i<this.songArray.length){
            const nextSong = this.songArray[this.i+1]
            //this.playSong(nextSong)
            return nextSong
        }else{
            return null
        }
    }
    
        getPreviousSong()
    {
        if(this.songArray && this.i > 0 && this.i<this.songArray.length){
            const nextSong = this.songArray[this.i-1]
            console.log(nextSong)
            //this.playSong(nextSong)
            return nextSong
        }else{
            return null
        }
    }


    loadSongs(song, playlist_song = "song")
    {
        if(playlist_song === "playlist"){
            this.songArray = song
            song.forEach(song=>{
                this.audio.src = song.src.aduioURL
                this.audio.load()
            })
        }else if(playlist_song === "song"){
            this.songArray.push(song)
        }
    }
    
      playSong(song)
    {
        this.song = song
        this.audio.src = song.src.aduioURL
        this.play(song)
    }

and in audio player:

function next(){
        const nextSong = song.getNextSong()
        if(nextSong)
        {
          song.playSong(nextSong)
        }
      }
      
      function previous(){
        const previousSong = song.getPreviousSong()
        if(previousSong)
        {
          song.playSong(previousSong)
        }
      }

It works perfectly but the problem of it is, i cannot change/skip the track from browser control. for eg:- in soundcloud and other apps If i am using it in mobile then i can skip the track from my lockscreen, There will be a small browser audio control and we can skip it from there. But from my app i cant do that for some reason.

heres the picture of what i am talking about:

soundcloud:

enter image description here

myapp:

enter image description here

as you can see here I cant control it from here. Where as in sound cloud i can change the tracks. And in soundlocud, it also displays title of the song where as in my it doesnt, it just displays title of my page.

I am using react for the development

Answer

Please checkout MediaSession documentation

Media Session Doc