Streaming an mp4 through a php file progressively

老子叫甜甜 提交于 2019-12-03 14:35:33

I think that you have a conceptual failure. You are treating the mp4 file like if it were a "raw data file". I try to explain myself.

Imagine that you have a text file, and you want to get the chars from position X. You can open the file, point the cursor to the correct position and then read byte by byte your text. This will work fine.

But now image that you want to do the same but with a text processor file. Would you expect the same results? No, because you have a lot of metadata in the file that prevents you from doing that.

Your problem is basically the same. You need to take in consideration the format of the file, managing the file with libraries designed for it, or doing by yourself.

The other option will be to work with raw data files, but in the case of video files, these are going to be really big files.

I hope that I helped you.

In addition to what dlopez said, I recommend to use 3rd-party solution for progressive download with seeking capabilities (AKA pseudo-streaming). You may take a look at the PD solutions listed in Wikipedia: https://en.wikipedia.org/wiki/Progressive_download

Most of them can also prevent video hotlinking protection as well.

C3RO14

I ran into a similar problem. Using stream_get_content($fp, $start) instead of fseek fixed the issue. I was able to get the video to stream fine on all browsers, and seeking (or skipping) throughout the video worked without a problem.

You can't use fseek(5654) if you are using file path with http://example.com...... You should use c:/file/abc.mp4 instead. It may solve your problem...

Fully Functional Code

$file = "z.mp4";
$length= filesize($file);
$offset = 0;
$f = fopen($file, 'r');
stream_get_contents($f, $offset);
$pos = 0;
while($pos < $length){
     $chunk = min($length-$pos, 1024*8);
     echo fread($f, $chunk);
     flush();
     ob_flush();
     $pos += $chunk;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!