Why will my embedded YouTube player not play automatically? - ios

I'm trying the following code on iOS in a UIWebView to embed a YouTube video:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
margin: 0;
padding: 0;
}
body, html {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<iframe id="player" type="text/html" width="100%" height="100%" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0"></iframe>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
</script>
</body>
</html>
I'm using the following Swift code to accomplish it:
let html = "<!DOCTYPE html><html><head><style type=\"text/css\"> body { margin: 0; padding: 0; } body, html { height: 100%; width: 100%; } </style> </head> <body> <iframe id=\"player\" type=\"text/html\" width=\"100%\" height=\"100%\" src=\"http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1\" frameborder=\"0\"></iframe> <script> var tag = document.createElement('script'); tag.src = \"https://www.youtube.com/iframe_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body></html>"
let width = UIScreen.mainScreen().bounds.width
let height = UIScreen.mainScreen().bounds.height
youTubeWebView = UIWebView(frame: CGRectMake(20, 120, width - 40, height-500))
youTubeWebView.mediaPlaybackRequiresUserAction = false
view.addSubview(youTubeWebView)
youTubeWebView.loadHTMLString(html, baseURL: NSBundle.mainBundle().resourceURL)
But though the video loads, it doesn't actually autoplay like it's supposed to.

Try to put ?rel=0&autoplay=1
<iframe id="player" type="text/html" width="100%" height="100%" src="http://www.youtube.com/embed/M7lc1UVf-VE?rel=0&autoplay=1" frameborder="0"></iframe>
Hopes that fix your problem.
BTW: can't be done in IOS/Mobile
"Warning: To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS — the user always initiates playback."
https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations

Related

Control several youtube videos

I'm looking for a way to control several iframe video on the same page with the same ID. I just want to mute them all but it only work for the first video. Here is my code ! Thanks !
<iframe id="ytplayer" type="text/html" width="100%" height="200px"
src="https://www.youtube.com/embed/bNkkFIjScY8?rel=0&showinfo=0&autoplay=1&controls=0&color=white&iv_load_policy=3&enablejsapi=1"
frameborder="0" allowfullscreen></iframe>
<iframe id="ytplayer" type="text/html" width="100%" height="200px"
src="https://www.youtube.com/embed/pKVvTKQgEH4?rel=0&showinfo=0&autoplay=1&controls=0&color=white&iv_load_policy=3&enablejsapi=1"
frameborder="0" allowfullscreen></iframe>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady() {
player.playVideo();
// Mute!
player.mute();
}
</script>

Chromecast + Youtube embed + HTML5 video tag = bug

I have been trying to play two videos (not necessarily simultaneously) on a Chromecast app. Once of them is embedded via the Youtube API and the other is a standard HTML5 video loaded via the tag.
It turns out that the Youtube video simply won't be played back on Chromecast if I also have a standard tag in my HTML5 page. But if I remove that video tag, then the Youtube video will play back nicely.
Any advice is highly appreciated!
Only one active video stream is supported on Chromecast.
I ran into this same problem.
The key elements to solve it are, unload the cast player and don't let a video tag linger in the DOM with a SRC attribute set when you attempt to play Youtube.
As for YouTube, dont let the IFRAME that contains their video player linger in the DOM either when attempting to use the HTML5 video tag.
You'll need to tear down the previous player before attempting to trigger playback through the opposing mechanism.
Here is my sample receiver I used to troubleshoot and solve the problem. This is a working example.
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #000;
overflow: hidden;
}
</style>
</head>
<body>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="//www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver.js"></script>
<script type="text/javascript" src="//www.gstatic.com/cast/sdk/libs/mediaplayer/1.0.0/media_player.js"></script>
<video id="chromecast" style="width: 50%; height: 50%;"></video>
<script>
var ytCode = 'sSwLhYhYgI0'
var hlsUrl = 'http://host.com/playlist.m3u8'
</script>
<!-- Chromecast -->
<script type="text/javascript">
var castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
var messageBus = castReceiverManager.getCastMessageBus('urn:x-cast:tv.domain');
cast.receiver.logger.setLevelValue(cast.receiver.LoggerLevel.DEBUG);
cast.player.api.setLoggerLevel(cast.player.api.LoggerLevel.DEBUG);
castReceiverManager.onReady = function() {
console.info('[castReceiverManager.onReady]');
castReceiverManager.setApplicationState('Ready');
};
castReceiverManager.onSenderConnected = function(sender) {
console.info('[castReceiverManager.onSenderConnected]', sender.userAgent);
};
messageBus.onMessage = function(event) {
var message = JSON.parse(event.data);
console.info('[messageBus.onMessage]', message);
};
// Normal
castReceiverManager.start({
maxInactivity: 8,
statusText: 'Ready to play',
dialData: undefined
});
window.playDirect = function(id) {
// Tear down any YT player
$('#youtube').remove();
if(!id) id = 'chromecast';
var mediaElement = document.getElementById(id);
window.host = new cast.player.api.Host({'mediaElement':mediaElement, 'url':hlsUrl});
window.host.onError = function(errorCode) {
console.log('ERROR ' + errorCode);
};
var protocol = cast.player.api.CreateHlsStreamingProtocol(window.host);
window.CCplayer = new cast.player.api.Player(window.host);
window.CCplayer.load(protocol, 25);
setTimeout(function() {
mediaElement.play();
}, 1000);
};
</script>
<!-- Youtube -->
<script>
window.onYouTubeIframeAPIReady = function() {
console.log('Initialized Youtube');
};
var playYT = function() {
// Tear down any direct player
if(window.CCplayer) {
window.CCplayer.unload();
}
$('video').attr('src', '');
// Inject div tag that will be converted to iframe with player
$('body').append('<div id="youtube" style="width: 50%; height: 50%;"></div>');
window.YTPlayer = new YT.Player(
'youtube',
{
height: '100%',
width: '100%',
playerVars: {
'autoplay': 0,
'controls': 0,
'cc_load_policy': 0,
'fs': 0,
'iv_load_policy': 0,
'modestbranding': 0,
'rel': 0,
'showinfo': 0,
'enablejsapi': 1
},
events: {
'onReady': function() {
var params = { videoId: ytCode, startSeconds: 170 };
window.YTPlayer.cueVideoById(params);
window.YTPlayer.playVideo();
},
'onError': function(err) {
console.log('YT Error ' + err);
}
}
});
};
var iframeScript = document.createElement('script');
iframeScript.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(iframeScript, firstScriptTag);
</script>
</body>
</html>
Test:
Load up the sample receiver above, and alternate the following inside the chrome debug console:
playDirect()
or
playYT()

Autoplay Youtube video in full screen and then redirect

I am having trouble redirecting youtube video after it finished playing using Youtube api.I have css code for styling but that doesn't really matter in this case. Any hep would be appreciated. EDIT: I would like this to be responsive. Here is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<LINK href="style.css" rel="stylesheet" type="text/css">
</HEAD>
<BODY>
<div class="video-container">
<iframe src="http://www.youtube.com/embed/sOS9aOIXPEk?autoplay=1" frameborder="0" width="560" height="315"></iframe>
</div>
</HTML>
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height=''
width=''
videoId: '0Bmhjf0rKe8',
playerVars:{'rel':0,'showinfo':1,'autoplay':1}
events: {
'onStateChange': onPlayerStateChange
}
});
}
// when video ends
function onPlayerStateChange(event) {
if(!event.data)
GoHome();
}
function GoHome(){
window.location = 'http://www.google.com';
}
</script>
When the video ends the event.data == 2. You also missed some comma's as separator of the object entries.
Here is a working example (Note: that the first iframe is commented-out):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<LINK href="style.css" rel="stylesheet" type="text/css">
</HEAD>
<BODY>
<!--
<div class="video-container">
<iframe src="http://www.youtube.com/embed/sOS9aOIXPEk?autoplay=1" frameborder="0" width="560" height="315"></iframe>
</div>
-->
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '768',
width: '1024',
videoId: '0Bmhjf0rKe8',
playerVars:{'rel':0,'showinfo':1,'autoplay':1},
events: {
'onStateChange': onPlayerStateChange
}
});
}
// when video ends
function onPlayerStateChange(event) {
//alert (event.data);
if (event.data == 0)
GoHome();
}
function GoHome(){
window.location = 'http://www.google.com';
}
</script>
</BODY>
</HTML>

Unable to play youtube video in window 8.1 winjs library

I am trying to play youtube video in my window 8.1 app, with the following code.
var videoPlayer = document.getElementById("videoPlayer");
var content = '<iframe width="480" height="270" src="http://www.youtube.com/embed/XGSy3_Czz8k?rel=0" frameborder="0" allowfullscreen></iframe>';
WinJS.Utilities.setInnerHTMLUnsafe(videoPlayer, content);
where the videoplayer is name of div where video player appears, but I am not able to play the video.
I have also tried using sample code from
https://developers.google.com/youtube/iframe_api_reference#Examples
but it didn't work as well. So please can anyone help me with this.
Thanks in advance
I managed to get this scenario to work for me, but I had to jump through some hoops to make it work.
First, in order to load the external script they need to communicate with the iframe, I had to sandbox the player in its own outer iframe that could run in the web context:
<div class="playerContainer">
<iframe class="playerFrame" src="ms-appx-web:///pages/video/iframe.html" style="visibility: hidden" scrolling="no"></iframe>
</div>
Then I had to edit my APPXMANIFEST to include the YouTube domain as a ContentURI rule:
https://*.youtube.com
My iframe.html was pretty simple:
<!DOCTYPE html>
<html>
<head>
<title>Video Player Iframe</title>
<link href="/pages/video/iframe.css" rel="stylesheet" />
<script src="/pages/video/iframe.js"></script>
</head>
<body>
<iframe id="player"
src="https://www.youtube.com/embed/?enablejsapi=1"
frameborder="0"
style="visibility: hidden"></iframe>
</body>
</html>
Then inside of iframe.js I borrowed heavily from https://developers.google.com/youtube/iframe_api_reference#Examples
(function () {
"use strict";
window.addEventListener('message', function (e) {
if (e.data.op === 'load') {
loadVideo(e.data.args)
} else if (e.data.op === 'resize') {
resize(e.data.args);
} else if (e.data.op === 'destroy') {
destroy();
}
});
var player;
var videoId;
function loadVideo(args) {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var playerEl = document.getElementById('player');
playerEl.height = window.innerHeight;
playerEl.width = window.innerWidth;
videoId = args.videoId;
window.onYouTubeIframeAPIReady = function onYouTubeIframeAPIReady() {
playerEl.style.visibility = 'visible';
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady
}
});
}
}
function resize(args) {
player && player.setSize(window.innerWidth, window.innerHeight);
}
function destroy() {
player && player.destroy();
player = null;
}
function onPlayerReady(event) {
event.target.loadVideoById(videoId);
}
})();
As you can see from the above, I am using iframe's postMessage to tell the wrapping iframe to load the videoId that I want:
iframe.addEventListener("load", function () {
iframe.style.visibility = 'visible';
if (iframe.contentWindow) {
iframe.contentWindow.postMessage({ op: "load", args: { videoId: video.id} }, "*");
}
});
Hope that helps some. The YouTube IFrame API is pretty finicky and didn't work right for me when loaded any other way.

play youtube video on click custom button

I do have following code where i want to play youtube video when button is clicked.
I have iframe code for youtube.
<script>
var player = document.getElementById("myplayer");
//Create a simple function and check if player exists
function play() {
if(player) {
player.playVideo();
}
}
</script>
<iframe id="myplayer" width="500" height="500" src="http://www.youtube-nocookie.com/embed/C-VoyCDUvr0?rel=0&wmode=Opaque&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
Play Youtube Video
But it does not play when i click on button / link
I put script code in head part of html and iframe and anchor link in body part of html.
Am i missing anything?
Here I gave the example of two players:
<!DOCTYPE html>
<html>
<body>
<div id="divPlayer1"></div>
<div id="divPlayer2"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1;
var player2;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('divPlayer1', {
height: '390',
width: '640',
videoId: 'iZYIsJ9i5yE',});
player2 = new YT.Player('divPlayer2', {
height: '390',
width: '640',
videoId: 'J7rKAKipj8s',});
}
function play1() {
player1.playVideo();
}
function play2() {
player2.playVideo();
}
</script>
Play Youtube Video1
Play Youtube Video2
</body>
</html>
There probably is no iframe#myplayer yet when your script is run. Move the definition of player inside the function like this:
function play() {
var player = document.getElementById("myplayer"); // Moved here
if(player) {
player.playVideo();
}
}
That should work.
Edit: That latter link seems to suggest you do this instead:
var player; // Might not be necessary
function onYouTubePlayerReady(playerId) {
player = document.getElementById("myplayer");
}
function play() {
if(player) {
player.playVideo();
}
}
<script>
function toggleVideo(state) {
var iframe = document.getElementById("myplayer").contentWindow;
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}
</script>
<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
<!-- popup and contents -->
<iframe id="myplayer" width="500" height="315" src="http://www.youtube.com/embed/C-VoyCDUvr0?enablejsapi=1"
frameborder="0" allowfullscreen></iframe>
Play Youtube Video
This is the working code with one play. Should be altered only by videoId: 'iZYIsJ9i5yE' whity our videoId in youtube:
<!DOCTYPE html>
<html>
<body>
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'iZYIsJ9i5yE',});
}
function play1() {
player1.playVideo();
}
</script>
Play Youtube Video
</body>
</html>
Use this iframe and change your youtube link. I hope it will work surely. It is working on my website.
<iframe src="https://www.youtube.com/embed/2XXzYCfBiAg" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen style="width:100%; height:445px; padding:0; left:25%"></iframe>

Resources