Problems with Youtube Iframe Api to start playing video on Chrome

冷暖自知 提交于 2021-01-21 08:12:00

问题


I have following starting setup:

var player;
function onYouTubeIframeAPIReady() {
   player = new YT.Player('player', {
      events: {
         'onReady': onPlayerReady,
         'onStateChange': onPlayerStateChange
      }
   });
}

Then in onPlayerReady handler I added event listener to button which is outside iframe:

function onPlayerReady(event) {
   button.addEventListener('click', () => event.target.playVideo());
}

In onPlayerStateChange I'm just logging what is happening:

function onPlayerStateChange(event) {
    console.log(event.data);
}

After hitting that button in Chrome (v.72.0.3626.119) there are 3 entries in console: -1 (UNSTARTED), 3 (BUFFERING), -1 (UNSTARTED). When I try to hit button again nothing happens. This works perfectly in Firefox, IE giving in console: -1 (UNSTARTED), 3 (BUFFERING),1 (PLAYING) and simply video starts playing.

Do you have any idea how to solve it?


回答1:


You have to add in the onPlayerReady function this line:

event.target.playVideo();

As is shown in the documentation:

Example:

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
  event.target.playVideo();
}

I can't say for sure why, but, in Google Chrome, for autoplay the video, you need to set the value 1 to the mute parameter, otherwise, autoplay the video wont work.

Example:

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '360',
    width: '640',
    videoId: '<YOUR_VIDEO_ID>',
    playerVars: {
      'autoplay': 1,
      'loop': 1,
      'mute': 1 // N.B. here the mute settings.
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

You can check this jsfiddle for guide yourself how you can set custom controls for play/pause your embed video.




回答2:


I have sent a key after load html, and it works for me.

KeyEvent k = new KeyEvent();
k.WindowsKeyCode = 0x0D;
k.FocusOnEditableField = true;
k.IsSystemKey = false;
k.Type = KeyEventType.Char;
webytb.GetBrowser().GetHost().SendKeyEvent(k);


来源:https://stackoverflow.com/questions/54944500/problems-with-youtube-iframe-api-to-start-playing-video-on-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!