简体   繁体   中英

How to play song on click?

I am wondering how to play a song when the song is clicked. Currently when I click on a song I have to click the play button the play it though I want it to auto play when I click on it. Before I had it working although the issue was that then the play button was all messed up. This is a link to the fiddle . This is my java script code.

$(function() {
    const audio = $('audio')[0];

    $('#player a').click(function(e) {
        e.preventDefault();

        $(this).find('i').toggleClass('fa-play-circle fa-pause-circle');

        if (audio.paused) {
            audio.play();
        } else {
            audio.pause();
        }
    });

    audio.ontimeupdate = () => {
        $('#progress').css('width', audio.currentTime / audio.duration * 100 + '%');
        $('#timer').text(formatTime(audio.currentTime));
    };

    audio.onended = () => {

    };

    $('#progress-bar').click(function(e) {
        e.preventDefault();
        audio.currentTime = e.offsetX / $(this).width() * audio.duration;
    });

    function formatTime(seconds) {
        let minutes = Math.floor(seconds / 60);
        seconds = Math.floor(seconds % 60);
        seconds = (seconds >= 10) ? seconds : '0' + seconds;
        return minutes + ':' + seconds;
    }
});
audioPlayer();
function audioPlayer(){
var currentSong = 0;
$("#audioPlayer")[0].src = $("#playlist li a")[0];
$("#playlist li a").click(function(e){
e.preventDefault();
$("#audioPlayer")[0].src = this;
$("#playlist li").removeClass("current-song");
currentSong = $(this).parent().index();
$(this).parent().addClass("current-song");
});
$("#audioPlayer")[0].addEventListener("ended", function(){
currentSong++;
if(currentSong == $("#playlist li a").length)
currentSong = 0;
$("#playlist li").removeClass("current-song");
$("#playlist li:eq("+currentSong+")").addClass("current-song");
$("#audioPlayer")[0].src = $("#playlist li a")[currentSong].href;
$("#audioPlayer")[0].play();
});
}

Put this on line 3 of your JSFiddle and it works:

$('#playlist li a').click( () => {
  audio.play();
  $('#player a i').removeClass('fa-play-circle');
  $('#player a i').addClass('fa-pause-circle');
} );

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