9

我有一个基本的音频播放器:

<audio controls="controls" autoplay="true" loop="loop">
<source src="song.php" type="audio/mpeg" />
</audio>

而不是直接指向 MP3 文件的源,我让它指向一个 PHP 文件,然后指向 MP3 文件,它可以工作。但是,当当前曲目结束时,PHP 文件指向一个新的 MP3 文件。所以,我遇到的问题是,当播放器循环播放新的 MP3 文件时,它完全停止工作。有没有办法解决?有没有办法通过播放列表或任何其他播放器来做到这一点?

4

4 回答 4

12

从您的重复问题中复制:


对于初学者,每次单击元素时都会附加一个新的事件处理程序。如果有人经常暂停音乐,他们就会遇到问题。

Intead,试试这个:

<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查询参数将确保每次都实际调用该文件。

于 2013-01-11T03:25:28.407 回答
1

我认为问题是您需要在当前歌曲完成后发出请求,您可以将ended事件侦听器添加到音频元素中来实现这一点:

HTML

<audio id="player" controls="controls" autoplay="true" loop="loop">
<source src="song.php" type="audio/mpeg" />
</audio>

Javascript

var audio = $("#player");
audio.addEventListener("ended", function(){
    $.post("song.php", function(result){
        audio.src = result;
        audio.pause();
        audio.load();//suspends and restores all audio element
        audio.play();
    });
});

注意:如果您仍然有问题,请在问题中包含 PHP 代码并检查您的 PHP 文件是否获得了正确的标题

于 2013-01-07T06:37:22.067 回答
1

随机选择是否必须由 php 完成?

If not, it will perhaps be simpler to tell javascript to select a random ID in a range. Then pass it to your php script as a GET parameter.

IN the php side, do a mapping of IDs > MP3 files, so that the same ID always correspond to the same MP3. You can use whatever you want: simple associative array, database, etc. In fact the IDs don't even have to be numbers.

IF you don't want that someone discover your mapping and said, call directly the wscript with ID X to download your MP3, you may change your mapping at each session for example.... the important thing is that a given ID always refer to the same MP3 at least during a reasonable period.

I whould also say that doing a redirection to the MP3 file from php may cause problems to some browsers. It is perhaps better to send the correct HTTP headers and actually return the file contents directly without redirecting. Quick example :

<?php
$file = "something.mp3";
header("Content-Type:audio/mpeg");
header("Content-LEngth:".filesize($file));
readfile($file);
?>

More info about readfile and header functions

于 2013-01-16T14:58:27.787 回答
0

Request ID也许最好的方法是在查询字符串中有一个唯一的变量。然后对于每个请求,您可以确定它是循环请求还是新请求或随机化的新请求。

你知道怎么做吗?如果没有,我将包含代码。

于 2013-01-07T05:22:22.163 回答