HTML5 audio ended function [duplicate]

落爺英雄遲暮 提交于 2019-12-18 09:04:32

问题


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';
    });
}

回答1:


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.



来源:https://stackoverflow.com/questions/14271082/html5-audio-ended-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!