Javascript HTML5 音频结束功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14271082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:14:07  来源:igfitidea点击:

HTML5 audio ended function

javascripthtmlhtml5-audio

提问by austinh

Possible Duplicate:
HTML5 audio element with dynamic source

可能的重复:
具有动态源的 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.

我试图让播放器在当前曲目结束后重新加载新曲目,但我想我可能做错了什么。

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

回答by Niet the Dark Absol

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.phpis a PHP file that returns the audio data. The nocachequery parameter will ensure that the file is actually called every time.

我假设这song.php是一个返回音频数据的 PHP 文件。该nocache查询参数将确保该文件实际上是所谓的每一次。