好吧,所以我在这个网站的某个地方找到了它,我尝试了一下,但这只是在控制台上塞满了很多错误,我没有弄错我在做什么
<?php
set_time_limit(0);
$dirPath = "masked on purpose";
$songCode = $_REQUEST['c'];
$filePath = $dirPath . "/" . $songCode . ".mp3";
$bitrate = 128;
$strContext=stream_context_create(
array(
'http'=>array(
'method'=>'GET',
'header'=>"Accept-language: en\r\n"
)
)
);
header('Content-type: audio/mpeg');
header ("Content-Transfer-Encoding: binary");
header ("Pragma: no-cache");
header ("icy-br: " . $bitrate);
$fpOrigin=fopen($filePath, 'rb', false, $strContext);
while(!feof($fpOrigin)){
$buffer=fread($fpOrigin, 4096);
echo $buffer;
flush();
}
fclose($fpOrigin);
?>
我要做的是制作一个在线广播流,该流扫描一个文件夹,并循环其中的所有.mp3文件
此处的修改: 我已将脚本更改为这样
<?php
set_time_limit(0);
$dirPath = "...";
$bitrate = 128;
$strContext=stream_context_create(
array(
'http'=>array(
'method'=>'GET',
'header'=>"Accept-language: en\r\n"
)
)
);
header('Content-type: audio/mpeg');
header ("Content-Transfer-Encoding: binary");
header ("Pragma: no-cache");
header ("icy-br: " . $bitrate);
$list = scandir($dirPath);
foreach($list as $file)
{
if($file== '.' or $file== '..')
continue; // skip, not a file or a folder
if(is_dir($file))
continue; // skip, not a file
echo $file . "<br>";
// define the file path
$filePath = $dirPath . '/' . $file;
// read the file
$fh = fopen($filePath, "r") or die("Could not open file.");
if ($fh) {
while (!feof($fh)) {
$buffer = fgets($fh, 4096);
echo $buffer;
flush();
}
fclose($fh);
}
}
?>
代码工作正常,但是问题是我希望流即使在没有人在听的情况下也能继续播放,每次有人尝试听它时,它都会重新启动。
答案 0 :(得分:0)
fopen
函数会将资源返回到打开的文件,如果失败则返回FALSE
布尔值。看来您的文件无法打开。检查$filePath
是否正确,并且$songCode
是否有值。
以下是读取文件夹中所有文件的代码:
// get a list of all files/folders in a path
$list = scandir($dirPath);
foreach($list as $file)
{
if($file== '.' or $file== '..')
continue; // skip, not a file or a folder
if(is_dir($file))
continue; // skip, not a file
// define the file path
$filePath = $dirPath . '/' . $file;
// read the file
$fh = fopen($filePath, "r") or die("Could not open file.");
if ($fh) {
while (!feof($fh)) {
$buffer = fgets($fh, 4096);
// Do something with the buffer here...
}
fclose($fh);
}
}