使用php将音频文件加载到html中


Load audio file into html using php

我有一个mp3文件存储在web根目录之外的位置。我可以通过传递一堆标题,使用php脚本下载该文件。然而,我希望能够直接播放它,在一个小音频播放器嵌入我的网站。

$file = '/location/testfile.mp3'; //this part works fine
header("Content-Transfer-Encoding: binary"); 
header("Content-Type: audio/mpeg");
header('Content-length: ' . filesize($file));
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');

这段代码位于我页面顶部的标记中,位于标记之前。在正文中,我想将$文件放入以下代码中进行播放:

<audio controls>
    <source src="<?php echo $file; ?>" type="audio/mp3">
    Your browser does not support the audio element.
</audio>

我看到一个播放器,它播放声音。然而,它涵盖了整个页面。我做错了什么?

我有一个播放音频文件的播放器,请在PHP中尝试以下代码来渲染音频文件:

$path = 'some/path/file.mp3';
$ch = curl_init($path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
    echo 'CURL Failed';
    exit;
}
if (preg_match('/Content-Length: ('d+)/', $data, $matches)) {
    $contentLength = (int) $matches[1];
}
header('Content-Transfer-Encoding: binary');
header('Content-Type: audio/mpeg');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . $contentLength);
ob_clean();
flush();
echo $data;
exit;