简体   繁体   中英

Looping through array of songs html5 audio

Loop stops at end when entire playsite is played, but it won't restart and set currentSong to 1? I have 8 songs in my array, it loops through each of them and plays them, when they end they call NextSong, but when the last song plays nothing happens.

function NextSong()
{
    alert("next song");
    document.removeEventListener('ended',NextSong);

    if(rewindClicked ==true)
    {
        currentSong--;
    }
    else
    {
        currentSong++;
    }

    if(currentSong > songList.length)
    {
        currentSong = 1; 
    }

    if(currentSong < 1)
    {
        currentSong = songList.length; 
    }

    songList[currentSong].play();
    rewindClicked = false;

    //song.addEventListener('ended', NextSong);
    songList[currentSong].addEventListener('ended', NextSong);
}

Arrary indexes start from 0.

if(currentSong > songList.length)
{
    currentSong = 1;
}

songList[currentSong].play();

This part allows currentSong to be exactly the array's length, which means songList[currentSong] tries to access an element out of bounds, which you might see in the JavaScript error console. In other words, if there are 8 songs in the array, songList[ 7 ] is the last of them.

Change the conditional to:

if(currentSong >= songList.length)

Similarly you might want to change

if(currentSong < 1)
{
    currentSong = songList.length; 
}

to

if(currentSong < 0)
{
    currentSong = songList.length - 1; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM