在 Chrome 的 HTML5 视频标签中通过 php 播放 mp4 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24596450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:22:58  来源:igfitidea点击:

Play mp4 file through php in HTML5 Video Tag in Chrome?

phpvideomp4

提问by beeb.vn

I have a problem with mp4 files. Html5 Video Tag can play it with direct link, but not with PHP Header (Mp3 is worked fine with PHP Header). I have tried almost of solution in Stack but still not resolve my problem :(

我的 mp4 文件有问题。Html5 Video Tag 可以用直接链接播放,但不能用 PHP Header 播放(Mp3 与 PHP Header 配合得很好)。我已经在 Stack 中尝试了几乎所有的解决方案,但仍然没有解决我的问题:(

Hear is my code:

听到是我的代码:

PHPmp4.php

PHPmp4.php

    error_reporting(0);

    $local_file = 'z.mp4';//'b.mp3';
    $download_file = 'out.mp4';
    // send headers
    header('Cache-control: private');
    header('Content-Type: video/mp4');
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);
    header('Accept-Ranges: bytes');
    header("Content-Transfer-Encoding: binary");
    readfile($local_file);

HTML

HTML

     <video controls="" autoplay="" name="media">
          <source src="http://localhost/videos/mp4.php" type="video/mp4">
     </video>

I don't know why :( Please help me.

我不知道为什么:(请帮助我。

Thanks,

谢谢,

回答by beeb.vn

OK! I've resolved my problem :) Hope this will help anyone has the same problem as me

好的!我已经解决了我的问题 :) 希望这会帮助任何和我有同样问题的人

Just use that code:

只需使用该代码:

$file = 'local_file';
$newfile = 'outFile';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($newfile));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

回答by Oguzhan Ozel

I think you've added unnecessary headers to your php file. Try this one:

我认为您在 php 文件中添加了不必要的标题。试试这个:

$local_file = 'z.mp4';
$size = filesize($local_file);

header("Content-Type: video/mp4");
header("Content-Length: ".$size);

readfile($local_file);

And a HTML code something like this

和一个像这样的 HTML 代码

<video width="480" height="320" controls>
  <source src="mp4.php" type="video/mp4">
</video>

EDIT:This will also work for mp3 files when you change Content-Type header and html video type.

编辑:当您更改 Content-Type 标题和 html 视频类型时,这也适用于 mp3 文件。

<video width="480" height="320" controls>
  <source src="mp3.php" type="audio/mpeg">
</video>