3

Possible Duplicate:
HTML5 audio element with dynamic source

I'm trying to get the player to reload a new track once the current one ends, but I think I might have done something wrong.

This is the player:

<audio id="audio" autoplay controls="controls" onclick="start()">
<source src="song.php" type="audio/mpeg" />
</audio>

Here's the script:

function start(){
    var audio = document.getElementById('audio');
    audio.play();
    audio.addEventListener('ended',function(){
        $.post("song.php", function(result){
        audio.src = result;
        audio.pause();
        audio.load();
        audio.play();
    });
    });
}

If I change the script to this, it works...but I don't want to reload the whole page:

function start(){
    var audio = document.getElementById('audio');
    audio.play();
    audio.addEventListener('ended',function(){
        window.location = 'player.html';
    });
}
Community
  • 1
  • 1
austinh
  • 941
  • 6
  • 12
  • 30

1 Answers1

10

For starters, you are attaching a new event handler every single time the element is clicked. If someone frequently pauses the music, they will run into problems.

Intead, try this:

<audio id="audio" autoplay controls src="song.php" type="audio/mpeg"></audio>
<script type="text/javascript">
    document.getElementById('audio').addEventListener("ended",function() {
        this.src = "song.php?nocache="+new Date().getTime();
        this.play();
    });
</script>

I'm assuming that song.php is a PHP file that returns the audio data. The nocache query parameter will ensure that the file is actually called every time.

Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
  • Thank you! This is what I was looking for :) – austinh Jan 11 '13 at 03:22
  • If you want to put this as the answer on http://stackoverflow.com/questions/14190160/html5-audio-element-with-dynamic-source/14191068 too, I'll accept it on that one as well. – austinh Jan 11 '13 at 03:24