HTML5音频结束功能 [英] HTML5 audio ended function
问题描述
可能重复:
带有动态源的HTML5音频元素
我'我试图让玩家在当前曲目结束时重新加载新曲目,但我认为我可能做错了。
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.
这是播放器:
<audio id="audio" autoplay controls="controls" onclick="start()">
<source src="song.php" type="audio/mpeg" />
</audio>
这是脚本:
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';
});
}
推荐答案
对于初学者,你正在附上每次单击元素时都有一个新的事件处理程序。如果有人经常暂停音乐,他们就会遇到问题。
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,试试这个:
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>
我假设 song.php
是一个返回音频数据的PHP文件。 nocache
查询参数将确保每次实际调用该文件。
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.
这篇关于HTML5音频结束功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!