php 立即提供 mp4(在加载所有内容之前)

Tho*_*Leu 1 php http-headers html5-video

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

当我使用常规 mp4 文件作为源时,视频很快就会开始播放,我还可以寻找尚未下载的部分。

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

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

...
<video src="http://videoserver.com/stream.php?file=videoxy.mp4">
...
Run Code Online (Sandbox Code Playgroud)

和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');
}
...
Run Code Online (Sandbox Code Playgroud)

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

如何在下载所有内容之前开始播放视频?另外我想寻求尚未下载的部分像以前一样工作。

Tho*_*Leu 5

我发现这个要点的解决方案是有效的:

...
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');
}
...
Run Code Online (Sandbox Code Playgroud)