php立即服务mp4(在加载所有内容之前)

时间:2016-02-10 09:44:37

标签: php http-headers html5-video

我正在实施一个提供mp4文件的HTML5视频播放器。

当我使用普通的mp4文件作为源时,视频很快就会启动,我也可以寻找尚未下载的部分。

现在,我想保护我的视频文件,即它们存储在网络根目录下,视频src是一个php文件,用于检查是否允许用户观看视频。

所以我的HTML看起来像这样:

...
<video src="http://videoserver.com/stream.php?file=videoxy.mp4">
...

和stream.php:

...
if ($access_granted) {
  if ($fd = fopen($path, "rb")) {
    $fsize = filesize($path);
    header("Content-Type: video/mp4");
    header("Content-Disposition: inline; filename=\"".$filename."\"");
    header('Content-Transfer-Encoding: binary');
    header("Content-Length: $fsize");
    fpassthru($fd);
  } else {
    die('file not found');
  }
} else {
  die('forbidden');
}
...

现在,视频仍会播放,但只有 视频完全下载后才能播放。

如何在下载所有内容之前启动视频?此外,我还想像以前一样寻找尚未下载的部件。

1 个答案:

答案 0 :(得分:3)

我发现此gist的解决方案正在运行:

...
if ($access_granted) {
  if ($fp = fopen($path, "rb")) {
    $size = filesize($path); 
    $length = $size;
    $start = 0;  
    $end = $size - 1; 
    header('Content-type: video/mp4');
    header("Accept-Ranges: 0-$length");
    if (isset($_SERVER['HTTP_RANGE'])) {
      $c_start = $start;
      $c_end = $end;
      list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
      if (strpos($range, ',') !== false) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
      }
      if ($range == '-') {
        $c_start = $size - substr($range, 1);
      } else {
        $range = explode('-', $range);
        $c_start = $range[0];
        $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
      }
      $c_end = ($c_end > $end) ? $end : $c_end;
      if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
      }
      $start = $c_start;
      $end = $c_end;
      $length = $end - $start + 1;
      fseek($fp, $start);
      header('HTTP/1.1 206 Partial Content');
    }
    header("Content-Range: bytes $start-$end/$size");
    header("Content-Length: ".$length);
    $buffer = 1024 * 8;
    while(!feof($fp) && ($p = ftell($fp)) <= $end) {
      if ($p + $buffer > $end) {
        $buffer = $end - $p + 1;
      }
      set_time_limit(0);
      echo fread($fp, $buffer);
      flush();
    }
    fclose($fp);
    exit();
  } else {
    die('file not found');
  }
} else {
  die('forbidden');
}
...