我正在尝试
<video>
标签流式传输视频(成块)。fseek()
和fread()
读取二进制文件,并将二进制数据发送回客户端(浏览器)。从浏览器向服务器发出AJAX请求,以获取二进制数据并从Object URL
中创建Blob
并将其分配给视频标签的src
。
以下代码仅获取视频的第一块。我本身无法成功流式传输。
PHP代码:
<?php
$fp = fopen("/var/www/html/../api/public/videos/6/jellyfish.mp4","r");
if($fp === false){
die("Could not open file");
}
header('accept-ranges:bytes');
header('Content-type:video/mp4');
header('Content-length:'.$_GET['offset']);
fseek($fp,intval($_GET['start']));
echo fread($fp,intval($_GET['offset']));
前端代码:
<html>
<head><title>Streaming a Video</title></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<video id='playThis' controls="controls" height="500" width="500">
Your browser does not support the video tag
</video>
<script>
$.ajax({
url:'http://localhost/code.php',
method:'GET',
data:{start:0,offset:1000},
xhrFields:{
responseType: 'blob'
},
success:function(response){
document.getElementById('playThis').src = URL.createObjectURL(response);
},
error:function(xhr){
console.log(xhr);
}
});
</script>
</body>
</html>
有人可以指引我正确的方向吗?