如何直接调用getvideotiming.php获取当前视频播放时间?
问题:直接调用getvideotiming.php无法获取视频播放时间的解决方案
问题分析
直接访问getvideotiming.php返回null的原因有两个:
- 直接访问时没有通过POST(或GET)传递
currentTime参数,PHP中$_POST['currentTime']不存在,因此返回默认值null - 视频的播放状态属于客户端浏览器的本地状态,后端PHP无法主动读取该数据,必须由前端将数据传递给后端或在本地存储后读取
解决方案
以下提供两种可行的实现方式:
方案一:让PHP支持GET/POST双参数获取
修改getvideotiming.php代码,同时支持POST和GET参数传递,这样直接访问时可以手动携带参数获取指定时间:
$amount = isset($_POST['currentTime']) ? $_POST['currentTime'] : (isset($_GET['currentTime']) ? $_GET['currentTime'] : null); echo "current time:".$amount;
使用示例:直接在浏览器地址栏输入 getvideotiming.php?currentTime=15,即可返回current time:15
方案二:自动同步前端播放时间并支持直接访问获取
通过前端localStorage存储实时播放时间,让getvideotiming.php自动读取该数据并返回结果:
- 修改
video.php的JavaScript代码,在播放时间更新时同步存储到localStorage:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <video id="video-active" class="video-active" width="640" height="390" controls="controls"> <source src="trial.mp4" type="video/mp4"> </video> <div id="current">0:00</div> <div id="duration">0:00</div> <script> $(document).ready(function(){ $("#video-active").on( "timeupdate", function(event){ onTrackedVideoFrame(this.currentTime, this.duration); }); }); function onTrackedVideoFrame(currentTime, duration){ $("#current").text(currentTime); $("#duration").text(duration); console.log(currentTime); // 把当前播放时间存入localStorage localStorage.setItem('activeVideoCurrentTime', currentTime); var amount = currentTime; $.ajax({ url: "getvideotiming.php", type: 'post', data: {"currentTime": amount}, success: function(response) { console.log("ys"); } }); } </script>
- 修改
getvideotiming.php,如果没有传递参数则自动读取localStorage的数据:
if(isset($_POST['currentTime']) || isset($_GET['currentTime'])){ $amount = isset($_POST['currentTime']) ? $_POST['currentTime'] : $_GET['currentTime']; echo "current time:".$amount; } else { // 输出前端脚本,读取localStorage后重新请求 ?> <script> var savedTime = localStorage.getItem('activeVideoCurrentTime') || 0; window.location.href = 'getvideotiming.php?currentTime=' + savedTime; </script> <?php }
现在直接访问getvideotiming.php时,会自动读取浏览器中存储的最新视频播放时间并返回结果。
注意事项
localStorage仅在同一域名、同一浏览器下有效,不同浏览器或设备无法共享数据- 如果需要跨设备或持久化存储播放时间,可以在
timeupdate事件中通过AJAX将时间保存到服务器数据库,此时getvideotiming.php可以直接从数据库读取最新时间
内容的提问来源于stack exchange,提问作者Bhagyashri
相关产品推荐
相关产品推荐

