如何使用HTML5获取YouTube JavaScript Player API以在Android上自动启动

时间:2014-08-08 19:34:06

标签: javascript android html5 youtube-api youtube-javascript-api

以下代码在所有操作系统和浏览器版本上正确执行并自动播放和HTML5 YouTube视频,但在Android中的chrome除外。是否有一个设置在Android操作系统修改或解决方法让这个视频以某种方式自动播放?必须有办法。

<div id="player"></div>

<script>

    var tag = document.createElement('script');
    tag.src = "http://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'u1zgFlCw8Aw',
            playerVars: { 'autoplay': 1, 'controls': 0, 'html5': 1 },

            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });



    }

    function onPlayerReady(event) {

    }

    function onPlayerStateChange(event) {

        if (event.data == YT.PlayerState.PLAYING ) {


        }
    }


</script>



    

2 个答案:

答案 0 :(得分:0)

尝试在玩家准备就绪时添加event.target.playVideo();

<强> HTML

<video id="player"></video>

<强> JS

let tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
let firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

let player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: 'u1zgFlCw8Aw',
        playerVars: { 'autoplay': 1, 'controls': 0, 'html5': 1 },

        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

function onPlayerReady(event) {
    event.target.playVideo();
}

function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING ) {
    }
}

答案 1 :(得分:0)

我尝试了martialdidit提供的答案但不幸的是,它加载了youtube播放器控件,但视频没有播放..

调查让我觉得在移动设备上,为了节省带宽,自动播放功能被禁用和禁止..发现这个链接的iOS,我想这是相同的android https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/AudioandVideoTagBasics/AudioandVideoTagBasics.html