加载视频文件到html5播放器与php

Load video file to html5 player with php

本文关键字:播放器 php html5 视频 文件 加载      更新时间:2023-09-26

我对视频没有什么问题。我刚刚创建了一个服务,用户将在每个页面上看到我们的应用程序只有一个帮助视频。

<

情况/strong>

当他点击视频图标时,弹出窗口将被打开-这个动作:

 var getVideoModal = function (video) {
  var path = '/application/files/help/tutorial_videos/'+video;
  $('div#modal-video').modal('show');
  $("#modal-video").draggable({
    handle: ".modal-header"
  });
  $('h3#modal-header-video').html(video);
  console.log(path);
  $("#video-help").find("#videoPath").attr("src", path);
  centerModal();
}

当弹出窗口打开时,(在弹出窗口正文中)有<video> html5元素

  <video id="video-help" width="530" controls>
    <source id="videoPath" src="" type="video/mp4">
  </video>

弹出窗口正常工作,但视频不能。

问题:

我有问题,因为我有视频存储在"/应用程序/帮助/视频"。这个路径是禁止的,你不能在浏览器中调用这个URL。我如何从这个受限的区域加载视频与PHP(有访问权限,通过文件系统)到我的视频播放器

我需要这样的东西:

  <video id="video-help" width="530" controls>
        <source id="videoPath" src="whatever.php?video=loaded.mp4" type="video/mp4">
  </video>    

这可能吗?

您可以有效地使用PHP从受限制的文件夹访问发送视频数据。打开、读取文件并发送数据。

如果用户通过按范围发送数据来移动玩家时间轴,你也可以让它工作。下面的代码是这样做的:

    $my_video_basename = //filter to have a trust filename
    $file = "/application/help/videos" . $my_video_basename;
    if(!file_exists($file)) return; 
    $fp = @fopen($file, 'rb');      
    $size   = filesize($file); // File size 
    $length = $size;           // Content length
    $start  = 0;               // Start byte
    $end    = $size - 1;       // End byte  
    header('Content-type: video/mp4');
    header("Accept-Ranges: 0-$length");
    header("Accept-Ranges: bytes"); 
    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);       
        ob_flush();    
    }
    fclose($fp);       
    exit();

好了,我找到了解决方案(PHP)。

这是一个很棒的PHP视频流类:

http://codesamplez.com/programming/php-html5-video-streaming-tutorial

这正是我所需要的。

注意:你需要有视频在HTML5支持的格式-我使用OGG -> sample.ogv

后端控制器仪表板为前端用户播放/停止视频

 <?php 
include 'conf.php';

    $sql="SELECT * FROM videos";
    $result=mysqli_query($conn,$sql);
    $file=mysqli_fetch_all($result,MYSQLI_ASSOC);

    $sqlnew="SELECT * FROM videos where Vid_is_active='Yes'";
    $resultnew=mysqli_query($conn,$sqlnew);
    $filenew=mysqli_fetch_all($resultnew,MYSQLI_ASSOC);
?>  
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

<script type="application/javascript">
var existData = '<?php echo @$filenew[0]['Vid_is_active']; ?>'; 
var existId = '<?php echo @$filenew[0]['Vid_id']; ?>';
$(document).ready(function () {   
    $(document).on('click', ".table .btn", function (e) {       
        $('#bsModal2').modal('show');
        e.preventDefault();
        id = $(this).attr('id')
        valu = $(this).val()
        if(valu==='Yes'){
        $(".stp_" + id).show();
        $(".btn-str").hide();
        }
        if(valu==='No'){
        $(".btn-str").show();
        $(".stp_" + id).hide();
        window.location.reload();
        //return false;
        }
    //return false; 
    if(existData==valu){
        $('#bsModal').modal('show');
        return false;
    }else{
        $.ajax({  
                url: 'http://localhost:8080/Ashish/VD/update.php',  
                type: 'POST',  
                dataType: 'json',  
                data: {"id": id,"value":valu},
                success: function (resultData) {  
                    console.log(resultData);
                    //update duration   
                    //window.location.reload();
                    if(valu=='Yes') {               
                     duartionupdat(id,valu);
                    }
                     //window.location.reload();
                }, 
                error: function (xhr, textStatus, errorThrown) {  
                    console.log('Error in Operation');  
                }  
            }); 
    }
    });

    function duartionupdat(id,valu){
        //alert(valu);
        var counter = 0;
            setInterval(function(){     
        counter++;          
                $.ajax({  
                url: 'http://localhost:8080/Ashish/VD/updateduration.php',  
                type: 'POST',  
                dataType: 'json',  
                data: {"id": id,"value":counter},
                success: function (resultData) {  
                }, 
                error: function (xhr, textStatus, errorThrown) {  
                    console.log('Error in Operation');  
                }  
            });     
        }, 1000);
    }
});
</script>   
                <div class="example" style="width: 221px;  background-color: #2faede;    margin: 2px 1202px 0;">
                <h3 class="txt" style="margin: 3px 65px -34px; color: white;">Shuffle</h3>
                <input id="toggle-event" type="checkbox" data-toggle="toggle" data-onstyle="success" data-offstyle="danger">
                <!--<div id="console-event"></div>-->
                <script>
                    $(function() {
                        $('#toggle-event').change(function() {
                        var t =$(this).prop('checked');
                        alert(t);
                        if(t==true){    
                        $(".example").css('background-color','green')
                        $(".txt").css('color','white')
                        }else{
                            $(".example").css('background-color','red')
                            $(".txt").css('color','white')
                        }

                            //$('#console-event').html('Toggle: ' + $(this).prop('checked'))
                        })
                    })
                </script>
            </div>          

 <div class="modal fade" id="bsModal2" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content" style="background-color: #e0fde0;">
            <div class="modal-header" style="margin: 10px 10px 11px;">
                <button type="button"  style="margin: -47px -43px 0px;"  class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4  style="margin: 0px 24px 15px;" class="modal-title" id="myModalLabel">Video Started!! Do not Refresh the page after play video!</h4>
            </div>   
        </div>
    </div>
</div>
<table class="table">
  <thead>
    <tr>
      <th scope="col">Sr.No.</th>
      <th scope="col">Video</th>
      <th scope="col">Name</th>
      <!--<th scope="col">Path</th>-->
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    <?php 
  $i=1;
  foreach($file as $files){  
  $video = $files['Vid_path']. $files['Vid_name'];
  ?>
    <tr>
      <th scope="row"><?php echo $i;  ?></th>
      <td><video style="background-color: #2faede;" id="myVideo" width='100' height='50'  ><source id="source_video" src="<?php echo $video  ?>" type="video/mp4"></video>
      </td>
      <td><?php echo $files['Vid_name'];  ?></td>
      <!--<td><?php echo $files['Vid_path'];  ?></td>-->
      <td>
        <button type="button" value="Yes" id="<?php echo $files['Vid_id'];  ?>"
          class="btn btn-str btn-success str_<?php echo $files['Vid_id']; ?>">Start</button>

        <button value="No" style="display:none;" id="<?php echo $files['Vid_id'];  ?>" type="button"
          class="btn btn-stp btn-danger stp_<?php echo $files['Vid_id']; ?>">Stop</button>
      </td>
    </tr>
    <?php
$i++;
} 
 ?>
  </tbody>
</table>

Fornt-end放像机

<?php 
    include 'conf.php';
    $sql="SELECT * FROM videos where  Vid_is_active='Yes'";
    $result=mysqli_query($conn,$sql);
    $file=mysqli_fetch_all($result,MYSQLI_ASSOC);
    $filename= @$file[0]['Vid_name'];
?>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="application/javascript">
      window.onload = function() {    
        setInterval(function(){ 
                $.ajax({  
                    url: 'http://localhost:8080/Ashish/VD/api.php',  
                    type: 'POST',  
                    dataType: 'json',  
                    data: 'Yes',  
                    success: function (resultData) {  
                        console.log(resultData); 
                        var path  =resultData[0]['Path'];
                        var vName = resultData[0]['videoName'];
                        var duration  =resultData[0]['duration'];
                        console.log(resultData);
                        if(resultData[0]['Status']==false){
                            //alert('Stoped');
                            window.location.reload();
                        }else{
                        $("#myVideo").html('<source id="source_video" src="'+path+vName+'" type="video/mp4">');
                        document.getElementById("myVideo").currentTime = duration;
                        //window.location.reload();
                        }
                    }, 
                    error: function (xhr, textStatus, errorThrown) {  
                        console.log('Error in Operation');  
                    }  
                });  
            }, 2000);
    }  
    </script>
                        <div class='row'>
                            <div class='column'>
                                <div class='card'>                          
                                    <video id="myVideo" width='1410' height='710'  autoplay ></video>
                                </div>
                            </div>
                        </div>

API.php

    include 'conf.php';
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
    header('Access-Control-Allow-Credentials: true'); 

        $query='Select * from videos  where Vid_is_active="Yes"';
        $result=mysqli_query($conn,$query);
        $file=mysqli_fetch_all($result,MYSQLI_ASSOC);
        $result=array();
        if(!empty($file)){
        //echo $sql;die;
        $result[] = array('duration'=>$file[0]["duration"],'id'=>$file[0]["Vid_id"],'Status'=>$file[0]["Vid_status"],'Path'=>$file[0]["Vid_path"],'videoName'=>$file[0]["Vid_name"] ,'message' => 'Video List');
        }else{
        $result[]=array('Status'=>false, 'message'=>'No vidoes are Active');    
        }
        echo json_encode($result);

Update.php

    include 'conf.php';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true'); 


    $sql="SELECT * FROM videos where Vid_is_active='Yes'";
        $result=mysqli_query($conn,$sql);
        $file=mysqli_fetch_all($result,MYSQLI_ASSOC);
    if($_POST['value']=='Yes'){

           $query='UPDATE videos SET Vid_status = "Started" , Vid_is_active="'.$_POST["value"].'" WHERE Vid_id ='.$_POST["id"].''; 
        }else{
         $query='UPDATE videos SET Vid_status = "Stop" , duration=0, Vid_is_active="'.$_POST["value"].'" WHERE Vid_id ='.$_POST["id"].'';
        }
        //echo $query;die;
        $result=mysqli_query($conn,$query);
        $results=array();
        $results[] = array('id'=>$_POST["id"],'Message'=>'Updated');
        echo json_encode($results);

Updateduration.php

    include 'conf.php';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true'); 
    $query='UPDATE videos SET duration ='.$_POST["value"].'  WHERE Vid_id ='.$_POST["id"].'';
    $result=mysqli_query($conn,$query);
    $results=array();
    $results[] = array('id'=>$_POST["id"],'Message'=>'Duration Updated');
    echo json_encode($results);