开发者

jQuery function audioElement ended doesn't work

I've got some code which creates an < audio > element and plays a song, when I click on a button. So far so good. The button turns from "Play Music" into "Stop Music" as it's clicked.

Now I added this code:

audioElement.addEventListener('ended', function() {
    $('span#pause').fadeOut('slow');
    $('span#play').delay(1500).fadeIn('slow');
});

Which technically should show the Play-Button again, when the song is over. But it doesn't. Could anybody tell my why?

Here's the whole code:

$(document).ready(function() {

var songList = [
    'song1.ogg',
    'song2.ogg',
    'song3.ogg'
];
var randomNumber = Math.floor(Math.random()*songList.length);

var audioElement = document.createElement('audio');
audioElement.setAttribute('src', songList[randomNumber]);
audioElement.load();

aud开发者_如何学JAVAioElement.addEventListener('ended', function() {
    $('span#pause').fadeOut('slow');
    $('span#play').delay(1500).fadeIn('slow');
});

$('#play').click(function() {
    audioElement.play();
    $('span#play').fadeOut('slow');
    $('span#pause').delay(1500).fadeIn('slow');
});

$('#pause').click(function() {
    audioElement.pause();
    $('span#pause').fadeOut('slow');
    $('span#play').delay(1500).fadeIn('slow');
});
});


The answer to your question in your comment to start the next song: change the src-attribute of the audio tag. E.g. add a new button called "next" and following script:

$('#next').click(function() {
    randomNumber = (randomNumber + 1) % songList.length;
    audioElement.setAttribute('src', songList[randomNumber]);
    $('#play').click();
});

Also see the updated jsfiddle.

=== UPDATE ===

  • First the randonNumber will be incremented. The modulo % (remainder of division) prevents, that the number is higher then the number of songs.
  • Then the source of the audio tag will be set to the next song.
  • At least a click event will be triggered, like somebody had clicked on the play button, so the play click handler starts the song and changes the button visibility.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜