前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >php输出字节流(本节以音频播放为例)

php输出字节流(本节以音频播放为例)

作者头像
Sindsun
发布2019-12-06 17:48:34
1.6K0
发布2019-12-06 17:48:34
举报
文章被收录于专栏:狂码一生狂码一生

本教程是在ThinkPHP5.0中进行的,如用在其它程序中,作少量修改即可。

代码语言:javascript
复制
    /**
     * 以文件流输出音频文件
     * @author Sindsun
     * @date 2018年10月27日22:32:17
     * @param $filePath 文件地址
     * @param $param 其它参数
     * @param $fun 执行一个闭包函数  第一个参数为外部参数
     * @output filestream
     * @return bool
     * */
    public function outputStream($filePath,$clientSectionInfo){
        if(!file_exists($filePath)){
            return false;
        }
        //返回的文件(流形式)
        //对照的完整地址推荐:http://tool.oschina.net/commons/
        //header("Content-type: application/octet-stream");
        //header("Content-type: audio/mp3");
		header("Content-type: audio/mpeg");
		header("Age:0");
        //按照字节大小返回
        //header("Accept-Ranges: bytes");
        $fileSize = filesize($filePath);
        //$httpRange = $this->request->header('HTTP_RANGE');
		$httpRange = $this->request->header('Range');
		if(empty($httpRange)){
			$httpRange = $this->request->header('HTTP_RANGE');
		}
        if(!empty($httpRange)){
            header("HTTP/1.1 206 Partial Content");
            list($name, $range) = explode("=", $httpRange);
            list($begin, $end) =explode("-", $range);
			if(empty($begin)){
				$begin = 0;
			}
			if(empty($end) || $end == 0){
				$end = $fileSize - 1;
			}
        }else{
            $begin = 0;
            $end = $fileSize - 1;
        }
        header("Content-Length: " . ($end - $begin + 1));
        //header("Content-Disposition: filename=".basename($filePath));
        //header("Content-Disposition: filename=".time().'.mp3');
        header("Content-Range: bytes " . $begin . "-" . $end . "/" . $fileSize);
		//header("Content-Range:bytes {$begin}-{$end}/{$fileSize}");
		header("Vary:Accept-Encoding");
		header("Cache-Control:max-age=315360000");
        $fobj = fopen($filePath, 'rb');
        ob_clean();
        flush();
        fseek($fobj, $begin);
        //设置分流
        $buffer = 1024 * 10;
        //来个文件字节计数器
        $count = 0;
        while(!feof($fobj)){
            $p = min($buffer,$end - $begin + 1);
            $begin += $p;
            $data = fread($fobj,$buffer);
            //$count += $buffer;//本次请求流量统计
            echo $data;    //传数据给浏览器端
        }
        fclose($fobj);
        
        //更新请求次数与
        /*$this->dbConObj('tab_client_sections')->where('id',$clientSectionInfo['c_id'])->update([
            'request_count' => $clientSectionInfo['request_count']+1,
            'traffic_count' => $clientSectionInfo['traffic_count']+$count
        ]);*/
        exit();
        //return true;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-10-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档