Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YouTube iFrame API: Programmatically play natively?

I'm attempting to play a YouTube video (within an iFrame) programmatically via JS. Here is the code I'm using to programmatically play a YouTube video:

iframe.postMessage('{"event":"command","func":"playVideo","args":""}', '*');

However, in devices that support YouTube's native playback feature, the video within the iFrame becomes a black screen and doesn't open up the native video player.

How can I use the iFrame API to programmatically playback a video natively when possible?

like image 723
wdews Avatar asked Sep 16 '14 17:09

wdews


People also ask

How do I Autoplay YouTube IFrame?

To make an embedded video autoplay, add "&autoplay=1" to the video's embed code right after the video ID (the series of letters that follows "embed/").

Can you play videos with YouTube API?

The IFrame player API lets you embed a YouTube video player on your website and control the player using JavaScript. Using the API's JavaScript functions, you can queue videos for playback; play, pause, or stop those videos; adjust the player volume; or retrieve information about the video being played.

How do I allow play embedded YouTube videos on one page?

enablejsapi=1' to the end of the embed URL. Essentially this manager keeps track of the registered videos. If it detects that a registered video begins to play it will pause any other registered video that is currently playing.


2 Answers

I highly recommend you to check the Youtube Iframe Player API. https://developers.google.com/youtube/iframe_api_reference#Playback_controls

var player;
  function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: 'M7lc1UVf-VE',
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerReady(event) {
  event.target.setVolume(100);
  event.target.playVideo();
}
like image 87
Jorge Vivas Avatar answered Oct 20 '22 03:10

Jorge Vivas


If you want to have the video autoplay when loaded, use this attribute in your JS: "autoplay:1". More info here: https://developers.google.com/youtube/player_parameters#autoplay

If you use the "onReady" event, you have to detect if the device allows autoplaying, which iOS does not. This is not an easy thing to test unless you use fragile UA sniffing. Using the built in method is much more reliable in this instance.

If you just want to play a video programmatically, you can use this method:

target.playVideo();

However, you again can not do this without user interaction on iOS. And it only works on iOS8, earlier versions will not allow JS to trigger the playing of videos.

like image 1
lostPixels Avatar answered Oct 20 '22 03:10

lostPixels