可见时自动播放媒体元素播放器

时间:2014-11-29 03:27:25

标签: jquery html5 mediaelement.js

我有一个wordpress网站,它使用原生播放器,mediaelement来显示视频。我尝试添加一些代码以便在可见时自动播放视频,在屏幕外时暂停。我一直在使用上一个问题here中的一段代码(使用isInViewport JQuery插件),但这里的播放/暂停事件似乎不会触发媒体元素播放器。我可以检测每个视频何时可见,并使用此处的滚动功能打印到控制台。根据我的阅读情况,我需要在调用播放/暂停功能之前初始化mediaelement播放器,但是我收到错误:" Uncaught TypeError:无法读取属性'播放器'未定义"每个滚动可以看到视频。

JQUERY:

$(function() {
    $(window).scroll(function() {
        $('.wp-video-shortcode').each(function() {
            var str = $(this).attr('id');
            var arr = str.split('-');
            typecheck = arr[0];
            if ($(this).is(":in-viewport") && typecheck == "video") {
                var video = new MediaElementPlayer($(this).attr('id'), {
                    success: function(mediaElement) {
                        $(this).attr('id')[0].player.pause(); 
                        console.log($(this).attr('id') + 'video is playing');

                    }
                });

                //$(this).[0].play();
            } else {
                //$(this).[0].pause();
            }

        });
    });
});

HTML:

<video class="wp-video-shortcode" id="video-1115-1" width="792" height="470" poster="http://cdn.ultrasoundoftheweek.com/post_files/uotw16.1.jpg" loop="1" preload="none" controls="controls">
<source type="video/mp4" src="http://cdn.ultrasoundoftheweek.com/post_files/uotw16.1.mp4?_=1" /> 
<source type="video/webm" src="http://cdn.ultrasoundoftheweek.com/post_files/uotw16.1.webm?_=1" /> 
</video>

1 个答案:

答案 0 :(得分:0)

对于任何正在努力解决这个问题的人来说,这是我的解决方案。 (此JQ上面的isInViewport和JQuery引用包含)。适用于Safari / Chrome / FF最新版本。不适用于移动设备。我将开始处理媒体查询并为android分开编码。

$(function() {
    $(window).scroll(function() {
        $('.wp-video-shortcode').each(function() {
            var str = $(this).attr('id');
            var arr = str.split('_');
            typecheck = arr[0];
            if ($(this).is(":in-viewport( 400 )") && typecheck == "mep") {
                    mejs.players[$(this).attr('id')].media.play();
                    console.log($(this).attr('id') + 'video is playing');
            } else if (typecheck == "mep") {
                    mejs.players[$(this).attr('id')].media.stop();
            }
        });
    });
});
相关问题