【问题标题】:Building a sequential video player构建顺序视频播放器
【发布时间】:2020-04-12 08:53:45
【问题描述】:

我有以下代码,我在 Chrome 中运行它,我启用了声音自动播放。路径加载到 src 中,但由于某种原因该播放不起作用。一旦一个完成,下一个应该开始,我仍然有循环遍历每个视频。但也许一次只做一件事,我该如何播放这个视频?

如果有人知道一个现成的实现,那就太好了。

文件结构...

/player/index.html
/player/media.json
/player/jquery-3.5.0.min.js
/player/media/a.mp4

index.html & media.json

<html>
<head>
    <title>Video Player</title>
    <style>
    body {
        background-color: black;
    }
    #video {
        position:absolute;
        z-index:-1;
        top:0;
        left:0;
        width:100%; 
        height:100vh;
    }
    </style>
</head>
<body>
    <video autoplay id="video">
    <source id="source" src="" type="video/mp4">
    </video>
</body>
<script src="jquery-3.5.0.min.js"></script>
<script>
    $(document).ready(function(){
    $.getJSON( "media.json")
    .done(function( json ) {
        var id = 0;
        var file ='media/' + json[id].file;
        $('#source').attr('src', file);
        $('#video').trigger('play');
    })
    .fail(function(jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log( "Request Failed: " + err );
    });
    });
</script>
</html>

[
    {"file" : "a.mp4"},
    {"file" : "a.mp4"},
    {"file" : "a.mp4"},
    {"file" : "a.mp4"}
]

【问题讨论】:

  • 尝试直接在媒体元素上调用play$('#video')[0].play()

标签: javascript jquery html video


【解决方案1】:

https://jsfiddle.net/kg6eq7po/1/

在 html 视频标签中清除来源

<video autoplay id="video"></video>

然后在您的成功方法中填充视频源。当你填写时,将活动类添加到第一个

json.forEach((x,index)=>{

    if(index==0){
       $('#video').append('<source class="active" id="source" src="'+x.file+'" type="video/mp4">');
    }
    else{
       $('#video').append('<source id="source" src="'+x.file+'" type="video/mp4">');
    }
})

最后添加通知视频是否结束的事件列表

var myvid = document.getElementById('video');
myvid.addEventListener('ended', function(e) {
  var activesource = document.querySelector("#video source.active");
  var nextsource = document.querySelector("#video source.active + source") || document.querySelector("#video source:first-child");

  // deactivate current source, and activate next one
  activesource.className = "";
  nextsource.className = "active";

  // update the video source and play
  myvid.src = nextsource.src;
  myvid.play();
});

【讨论】:

  • 是的,我重新加载了视频标签,效果很好,不知道我只需要重新加载源标签,这样可以节省一点。当我让它运行时,它呻吟着我需要交互,所以我只是在身体上放了一个 onclick 并解决了它。我为 127.0.0.1 启用了它并在那里尝试了 localhost 我的错,但点击事件我不需要浏览器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 2015-10-12
  • 2016-08-20
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
相关资源
最近更新 更多