Автоматически воспроизводить следующий трек в плейлисте

Я следил за учебным пособием о том, как создать медиаплеер для некоторых треков... Все работает так, как я хотел, за исключением того, что каждая песня воспроизводится, а затем останавливается... Я хотел бы, чтобы весь плейлист воспроизводился... то есть чтобы следующий трек начинался автоматически после того, как закончился предыдущий...

Я читал, что мне следует использовать прослушиватель событий в сочетании с методом 'end()'... хотя я безуспешно пытался. Любая помощь в этом будет принята с благодарностью...

Вот мой код... HTML:

<html>
<head>
    <title>HTML5 Audio Player</title>
    <link rel="stylesheet" href="css/style.css">
</head>

<body>
    <div id="container">
        <div id="audio-image">
            <img class="cover">
        </div>
        
        <div id="audio-player">
            <div id="audio-info">
                <span class="artist"></span> - <span class="title"></span>
            </div>
            <input id="volume" type="range" min="0" max="10" value="4">
            <br>
            <div id="buttons">
                <span>
                    <button id="prev"></button>
                    <button id="play"></button>
                    <button id="pause"></button>
                    <button id="stop"></button>
                    <button id="next"></button>
                </span>
            </div>
            <div class="clearfix"></div>
            <div id="tracker">
                <div id="progress-bar">
                    <span id="progress"></span>
                </div>
                <span id="duration">0:00</span>
            </div>
            <div class="clearfix"></div>
            <ul id="playlist" class="hidden">
                <li song="advert-1.mp3" cover="cover1.jpg" artist="Miss Ramos">advert-1.mp3</li>
                <li song="advert-2.mp3" cover="cover1.jpg" artist="Miss Ramos">advert-2.mp3</li>
                <li song="advert-3.mp3" cover="cover1.jpg" artist="Miss Ramos">advert-3.mp3</li>
                <li song="advert-4.mp3" cover="cover1.jpg" artist="Miss Ramos">advert-4.mp3</li>
                <li song="audiobook-part-1.mp3" cover="cover1.jpg" artist="Miss Ramos">audiobook-part-1.mp3</li>
                <li song="audiobook-part-2.mp3" cover="cover1.jpg" artist="Miss Ramos">audiobook-part-2.mp3</li>
                <li song="telephon-1.mp3" cover="cover1.jpg" artist="Miss Ramos">telephon-1.mp3</li>
            </ul>
        </div>
    
    </div>
    <script src="js/jquery-3.5.1.js"></script>
    <script src="js/main.js"></script>
</body>    
    
</html>

CSS:

*{
    margin:0;
    padding:0;
    border:none;
    outline:none;
}

body{
    font-family:Arial;
    font-size:13px;
    line-height:1.5em;
    color:#fff;
    
    background:#78284a; /* old browsers */
    background:-moz-linear-gradient(left, #78284a 0%, #6d8a9f 100%); /* FF3.6+ */
    background:-webkit-gradient(linear, left top, right top, color-stop(0%,#78284a), color-stop(100%,#6d8a9f));
    background:-webkit-linear-gradient(left, #78284a 0%, #6d8a9f 100%); /* Chrome10+, Safari5.1+ */
    background:-o-linear-gradient(left, #78284a 0%, #6d8a9f 100%); /* Opera 11.10+ */
    background:-ms-linear-gradient(left, #78284a 0%, #6d8a9f 100%); /* IE10+ */
    background:linear-gradient(to right, #78284a 0%, #6d8a9f 100%); /* W3C */
}

.clearfix{
    clear:both;
}

#container{
    width:330px;
    min-height:400px;
    background:#333;
    overflow:auto;
    margin:20px auto;
    border-radius:10px;
    box-shadow:0 10px 8px -8px #333;
}

#audio-image{
    position:relative;
    overflow:hidden;
    height:200px;
    margin-bottom:15px;
}

#audio-image .cover{
    width:100%;
}

#audio-info{
    text-align:center;
    margin-bottom: 7px; // added by self;
}

#audio-info .artist{
    font-weight:bold;
}

input#volume{
    width:95%;
    margin-left:2%;
/*    -webkit-appearance:none !important;   browser vol sytles overridden in vid*/
    background:#ccc;
    height:1px;
    margin-bottom:20px;
}

input#volume::-webkit-slider-thumb{
/*
    -webkit-appearance:none !important; browser volume styles overriden in vid
    background:url(../images/knob.png) no-repeat;   knob png required
*/
    height:12px;
    width:12px;
}

#buttons{
    width:90%;
    display:block;
    margin:15px auto;
    margin-left:23px;
    overflow:auto;
}

button#play{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/circled-play.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;
    margin-left:-2px;
}


button#pause{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/circled-pause.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;
    margin-left:-2px;
}

button#stop{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/stop-circled.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;
    margin-left:3px;
}

button#prev{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/rewind-button-round.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;
    margin-top:0; /*vid set to 15px*/
}

button#next{
    width:50px;     /*vid values set to 70px*/
    height:50px;    /*vid values set to 70px*/
    background:url(../images/fast-forward-round.png);
    background-size:cover;      /*look for background short-hand*/
    background-repeat:no-repeat;
    background-position:center center;
    float:left;     /*vid value set 'right'*/
    margin-left:0px;    /*vid value set 15px*/
}

#tracker{
    position:relative;
    width:100%;
}

#progress-bar{
    width:80%;
    margin-left:2%;    /*vid set to 2% */
    margin-bottom:20px;
    margin-top:9px;
    height:10px;
    background:url(../images/progress-bar.png) no-repeat;
    float:left;
}

#progress{
    background:url(../images/ ) no-repeat;  /* remember to update this selector (watch chap45 @ 08:36) */
    height:10px;
    display:inline-block;
}

#duration{
    position:absolute;
    top:0;
    right:10px;
    padding: 4px 8px;
    background:#000;
    border-radius:5px;
}

#playlist{
    list-style:none;
}

#playlist li{
    cursor:pointer;
    margin:5px;
}

#playlist li.active{
    font-weight:bold;
    padding:3px;
    background:#666;
}

Javascript [main.js]

var audio;

//Hide Pause
$('#pause').hide();

initAudio($('#playlist li:first-child'));

function initAudio(element){
    var song = element.attr('song');
    var title = element.text();
    var cover = element.attr('cover');
    var artist = element.attr('artist');
    
    //Create audio object
    audio = new Audio('media/'+ song);
    
    //Insert audio info
    $('.artist').text(artist);
    $('.title').text(title);
    
    //Insert song cover
    $('img.cover').attr('src','images/covers/'+cover);
    
    $('#playlist li').removeClass('active');
    element.addClass('active');
}



//Play button
$('#play').click(function(){
    audio.play();
    $('#play').hide();
    $('#pause').show();
    showDuration();
});

//Pause button
$('#pause').click(function(){
    audio.pause();
    $('#play').show();
    $('#pause').hide();
});

//Stop button
$('#stop').click(function(){
    audio.pause();
    audio.currentTime = 0;
});

//Next button
$('#next').click(function(){
    audio.pause();
    var next = $('#playlist li.active').next();
    if(next.length == 0){
        next = $('playlist li:first-child');
    }
    initAudio(next);
    audio.play();
    showDuration();
});

//Prev button
$('#prev').click(function(){
    audio.pause();
    var prev = $('#playlist li.active').prev();
    if(prev.length == 0){
        prev = $('playlist li:last-child');
    }
    initAudio(prev);
    audio.play();
    showDuration();
});

//Playlist song click
$('#playlist li').click(function(){
    audio.pause();
    initAudio($(this));
    $('#play').hide();
    $('#pause').show();
    audio.play();
    showDuration();
});

//Volume control
$('#volume').change(function(){
    audio.volume = parseFloat(this.value / 10);
});

//Time/Duration
function showDuration() {
    $(audio).bind('timeupdate',function(){
        //Get hours and minutes
        var s = parseInt(audio.currentTime % 60);
        var m = parseInt(audio.currentTime / 60) % 60;
        
        if(s < 10) {
            s = '0'+s;
        }
        $('#duration').html(m + ':'+ s);
        var value = 0;
        if(audio.currentTime > 0){
            value = Math.floor((100 / audio.duration) * audio.currentTime);
        }
        $('progress').css('width',value+'%');
    });
}

Все мультимедиа и изображения работают нормально... Пока я доволен тем, что у меня есть. Это просто вышеупомянутая проблема с треклистом, который не воспроизводится последовательно от начала до конца.

Большое спасибо...


person Chris Andrew    schedule 01.10.2020    source источник
comment
вы можете сделать audio.addEventListener с завершенным   -  person Jerson    schedule 01.10.2020
comment
audio.addEventListener('ended',function(){ // поместите сюда мою функцию... }); это сработает... не все ли равно, где разместить эту функцию? а также... я думал, что могу повторно использовать функцию "следующая", связанная с кнопкой "следующая"...   -  person Chris Andrew    schedule 01.10.2020
comment
добавлен ответ, пожалуйста, посмотрите   -  person Jerson    schedule 01.10.2020
comment
О, хорошо... большое спасибо... Я поднял ваш ответ, хотя он не появится в ветке, так как я новичок... еще раз спасибо...   -  person Chris Andrew    schedule 01.10.2020
comment
Добро пожаловать, рад помочь вам   -  person Jerson    schedule 01.10.2020


Ответы (1)


Вы можете использовать AddEventListener с завершенным событием

 audio.addEventListener('ended',function(){
   var next = $('#playlist li.active').next();
   if(next.length == 0){
      next = $('playlist li:first-child');
   }
   initAudio(next);
   audio.play();
   showDuration();
});

Вы можете поместить это в функцию initAudio

person Jerson    schedule 01.10.2020