使用PHP从URL读取MP4文件

时间:2016-09-29 06:05:46

标签: php html5 video http-headers mp4

我使用下面的代码片段来使用PHP读取mp4文件并在视频标记中播放它。当我将视频作为文件(test.mp4)调用localhost中允许来回移动搜索引擎时,此代码有效。但是当我使用视频源作为网址(http://techslides.com/demos/sample-videos/small.mp4)时,视频正在播放,但无法将搜索者前后移动。

$filename = 'http://techslides.com/demos/sample-videos/small.mp4'; 
             $mimeType = 'video/mp4';

              $ch = curl_init($filename);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
              curl_setopt($ch, CURLOPT_HEADER, TRUE);
              curl_setopt($ch, CURLOPT_NOBODY, TRUE);

              $data = curl_exec($ch);
              $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);

              curl_close($ch);

            // echo $size  = filesize($filename);die;
              $time  = date('r', filemtime($filename));

              $fm = @fopen($filename, 'rb');
              if (!$fm)
              {
                header ("HTTP/1.1 505 Internal server error");
                return;
              }

              $begin  = 0;
              $end  = $size - 1;

              if (isset($_SERVER['HTTP_RANGE']))
              {
                if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
                {
                $begin  = intval($matches[1]);
                if (!empty($matches[2]))
                {
                  $end  = intval($matches[2]);
                }
                }
              }
              if (isset($_SERVER['HTTP_RANGE']))
              {
                header('GET HTTP/1.1 206 Partial Content');
              }
              else
              {
                header('HTTP/1.1 200 OK');
              }

              header("Content-Type: video/mp4");
              header('Accept-Ranges: bytes');
              header("Content-Disposition: inline;");
              header("Content-Range: bytes $begin-$end/$size");
              header("Content-Transfer-Encoding: binary\n");
              header('Cache-Control: public, must-revalidate, max-age=0');
              header('Pragma: no-cache');  
              header('Content-Length:' . (($end - $begin) + 1));
              if (isset($_SERVER['HTTP_RANGE']))
              {
                header("Content-Range: bytes $begin-$end/$size");
              }
              header('Connection: close');
              $cur  = $begin;
              fseek($fm, $begin, 0);

              while(!feof($fm) && $cur <= $end && (connection_status() == 0))
              {
                print fread($fm, min(1024 * 16, ($end - $cur) + 1));
                $cur += 1024 * 16;
                usleep(1000);
              }

1 个答案:

答案 0 :(得分:1)

我之前尝试过这样做, 它没有用,因为fseek()不支持http, 该文件必须是“可搜索的”,这意味着您必须从路径

获取文件

检查此答案https://stackoverflow.com/a/21722576/5380308