在我们的平台上(基于Laravel 5.1),我们为注册用户提供音频和视频内容。当然,媒体文件存储在docroot
之外。
所以我使用一种方法来提供所请求的内容。这适用于除Android(本机或Chrome)之外的任何浏览器和操作系统。 Android对音频和视频标记使用字节范围请求。以下代码在开始时工作,并且暂时停止工作。我不知道为什么。任何:
public function loadfile(Request $request, $type, $filename="")
{
$filepath = $mediadirectory . $filename;
if (File::isFile($filepath)) {
$file = File::get($filepath);
$mimetype = File::mimeType($filepath);
$size = File::size($filepath);
if ($mimetype=="audio/mpeg" || $mimetype=="video/mp4") {
$stream = fopen($filepath, "r");
$start = 0;
$length = $size;
$status = 200;
$headers = ['Content-Type' => $mimetype, 'Content-Length' => $size, 'Accept-Ranges' => 'bytes'];
if (false !== $range = $request->server('HTTP_RANGE', false)) {
list($param, $range) = explode('=', $range);
if (strtolower(trim($param)) !== 'bytes') {
header('HTTP/1.1 400 Invalid Request');
exit;
}
list($from, $to) = explode('-', $range);
if ($from === '') {
$end = $size - 1;
$start = $end - intval($from);
} elseif ($to === '') {
$start = intval($from);
$end = $size - 1;
} else {
$start = intval($from);
$end = intval($to);
}
$length = $end - $start + 1;
$status = 206;
$headers['Content-Range'] = sprintf('bytes %d-%d/%d', $start, $end, $size);
$headers['Connection'] = "keep-alive";
}
$response=new StreamedResponse(function() use ($stream, $start, $length) {
fseek($stream, $start, SEEK_SET);
echo fread($stream, $length);
fclose($stream);
}, $status, $headers);
return $response->send();
} else {
return response($file, 200)->header('Content-Type', $mimetype)->header('Content-Length', $size)->header('Content-Disposition', 'filename="' . $filename . '"');
}
}
}
html是直接的html5:
<audio controls preload="auto">
<source src="/loadfile/principiante.mp3" type="audio/mpeg">
</audio>