PHP+HTML使用Blob对象实现媒体播放功能

参考:https://blog.csdn.net/SVictorique/article/details/54892701

后端tp5.1实现代码:

public function video(){
    return view();
}

// 下载视频文件
public function videoDownload(){
    $filePath = 'd:/22.mp4';
    if (file_exists($filePath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($filePath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: '.filesize($filePath));
        readfile($filePath);
        exit;
    }
}

前端:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h2>测试视频文件以blob的形式播放</h2>

<video id="video" width="500" height="300" controls="controls"></video>

<script type="text/javascript">
    //创建XMLHttpRequest对象
    var xhr = new XMLHttpRequest();
    //配置请求方式、请求地址以及是否同步
    xhr.open('POST', "{:url('videoDownload')}", true);
    //设置请求结果类型为blob
    xhr.responseType = 'blob';
    //请求成功回调函数
    xhr.onload = function (e) {
        if (this.status == 200) {
            //获取blob对象
            var blob = this.response;
            console.log(blob);
            //获取blob对象地址,并把值赋给容器
            document.getElementById('video').src=URL.createObjectURL(blob);
        }
    };
    xhr.send();
</script>
</body>
</html>
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注