首页 文章

用于平板电脑/手机的视频自动播放嗅探器 - “canPlayType”不适用

提问于
浏览
1

我想嗅出不支持视频自动播放的平台(手机,平板电脑) . 有可靠的方法来做到这一点吗?截至目前,我唯一的另一种选择似乎是一个完全有用的嗅探器 .

相关:用于嗅探手持设备的@media查询是否可靠?我想如果设备返回"landscape"或"portrait",它可能是一个手持设备,因此有点不太可能支持自动播放?

感谢您加入此讨论!

1 回答

  • 1

    landscapeportrait 查询只会真正告诉你浏览器窗口的宽高比,所以不可靠

    理论上, handheld 媒体查询将正确响应当前浏览器,并且在媒体查询中它似乎有效

    <style> 
    @media handheld only { body { background: #00ff00};}
    </style>
    

    但是当在代码中测试 handheld 属性时我运气不好( handheld 总是为我返回false,而 screen 总是返回true)

    if (window.matchMedia('handheld').matches) {
        // do some code for a handheld device
    }
    

    所以......计划B的时间

    我能想到可靠测试的唯一方法是尝试自动播放,同时触发定时器...如果视频在定时器触发时没有开始播放,则认为它不能 . 这不是一个优雅的解决方案(并且需要一些捏造才能让计时器正确考虑视频/缓冲的大小等)并且您可能想要对结果进行cookie,这样您就不必浪费时间 - 及时访问的时间 .

    在此示例中,我使用.5s延迟,并检查 <video> 标签上的 progress 事件......具体取决于您可能要尝试的场景和视频大小等 . 在iPad,Nexus7,Nexus4和Kindle HDX上进行了测试,看起来相当可靠

    <video id="videoPlayer" autoplay controls>
        <source src="Video.mp4" type="video/mp4">
    </video>
    
    <script>
    var playing = false
    var waitAndSee = 500; // this allows 0.5s for the video to show progress
    
    var video = document.getElementById('videoPlayer');
    video.addEventListener('progress',function(e){
        playing = true
    }); 
    
    var counter=setTimeout ( "didItStart()", waitAndSee );
    
    function didItStart() { 
        clearTimeout(counter);
        if (playing) {
        document.write("it started")
        } else {
        document.write("it didn't")
        }
    }
    
    </script>
    

相关问题