how to stop the youtube video playing in Ionic App - youtube

I am using IFrame for playing youtube video. It works fine but I want to stop it on button click. How to do it. Please help.
<div class="padding-css">
<iframe ng-model="myframe" class="frameclass" src="https://www.youtube.com/embed/CR5zjazP3hg?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>

Solution for Ionic2
ionViewWillLeave() {
let listaFrames = document.getElementsByTagName("iframe");
for (var index = 0; index < listaFrames.length; index++) {
let iframe = listaFrames[index].contentWindow;
iframe.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
}
Don't forget to enable JS at the end of the video link *?enablejsapi=1

You can create iframe through java script and control player through buttons as stop.
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
For more details you can go through this link.
https://developers.google.com/youtube/iframe_api_reference#Getting_Started

Related

Youtube API; shuffle playlist?

So for some time now I am trying to make a proper shuffle script, using the youtube api, in order to play my youtube playlist.
I've found a lot of examples, but none of them seem to be working very well. Some do shuffle the list but not the first song being played, and some do the precise opposite.
What I would like is to shuffle the full playlist and then start playing. So the first played song should be random and the next one played should be random/shuffled as well.
Ive found the script below to shuffle the playlist. However the first song played is not shuffled. Can someone help me out with this?
Thanks a million!
<html>
<body>
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
function onYouTubeIframeAPIReady() {
var player = new YT.Player("player", {
height: '390',
width: '640',
events: {
'onReady': function (event) {
event.target.cuePlaylist({list: "PLFgquLnL59anYA8FwzqNFMp3KMcbKwMaT"});
event.target.playVideo();
setTimeout(function() {
event.target.setShuffle({'shufflePlaylist' : true});
}, 1000);
}
}
});
}
</script>
</body>
</html>
This worked for me!
<html>
<body>
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
function onYouTubeIframeAPIReady() {
var numPl = Math.floor((Math.random() * 50) + 1);
var player = new YT.Player("player", {
height: '390',
width: '640',
playerVars: {
listType:'playlist',
list:'PLFgquLnL59anYA8FwzqNFMp3KMcbKwMaT',
index: numPl,
autoplay: 1,
},
events: {
'onReady': function (event) {
//event.target.cuePlaylist({list: "PLFgquLnL59anYA8FwzqNFMp3KMcbKwMaT"});
//event.target.playVideo();
setTimeout(function() {
event.target.setShuffle({'shufflePlaylist' : true});
}, 1000);
}
}
});
}
</script>
</body>
</html>
This works using youtube api. and users youtube created play list . shuffles the play list into new order every time page is refreshes
Load YT-player API.
Load YT-playlist user playlist id "**.youtube.com/playlist?list=PLo16_*******"
To Shuffle playlist use > player.setShuffle(true);
To Start YT-player at video 1 in shuffled playlist use > player.playVideoAt(0)
working demo Responsive shuffled YouTube Playlist on Google sites
code jsfiddle.net
<!DOCTYPE html>
<html>
<!-- Responsive YouTube shuffled playlist player -->
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag.
style = replaces size in the player script makes it responsive -->
<div style=" top: 0; left: 0; width: 100%; height: 100%; position: absolute;"
id='player'>
</div>
</body>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
playerVars: {
autoplay: 0,
loop: 1,
controls: 1,
showinfo: 1,
frameborder: 1,
'listType': 'playlist',
'list': "PLo16_DLriHp4A8BvkJFZfO_4KDVv7yGgy", // your YouTube playlist id here
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
// first shuffle play list
player.setShuffle(true);
// Onload and on refresh shuffles the users YT playlist but always starts playing
// the first video in the original list at its new index position
//ie. video (1) = video( new shuffled pos ?)
// to get over this we can start the player at the new shuffled playlist
//video 1(index=0) this changes every time it's refreshed
player.playVideoAt(0)
}
// 5. The API calls this function when the player's state changes.
// option to to add bits
function onPlayerStateChange(event) {
const player = event.target;
}
</script>
</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.

YouTube API - Enbedding By URL

I want to Embed A youtube video by url, example= https://gdata.youtube.com/feeds/api/users/estXcrew/uploads?max-results=1
This Is the block of code that I used
<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 player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '200',
width: '200',
videoId: '//video ID Usually goes here',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
I Copied this code from the Site of the Youtube API since I don't have much experience with it yet. How do I replace the "videoId" Line with the link above?
To load a YouTube video replace
//video ID Usually goes here
with the ID of the video you want to load.
Example YouTube video: http://www.youtube.com/watch?v=xmP7kQdAPhM
Now in the videoId I would use
videoId: 'xmP7kQdAPhM'
Or if you used some PHP you could try something like the following.
<?php
$feedURL = 'http://gdata.youtube.com/feeds/api/users/estXcrew/uploads?max-results=1';
$sxml = simplexml_load_file($feedURL);
$i=0;
foreach ($sxml->entry as $entry) {
$media = $entry->children('media', true);
$watch = (string)$media->group->player->attributes()->url;
$pat = '/\=([^\"]*?)\&/';
$value=$watch ;
preg_match($pat, $value, $matches);
echo "<iframe title='YouTube video player' class='youtube-player' type='text/html'
width='640' height='390' src='http://www.youtube.com/embed/$matches[1]'
frameborder='0' allowFullScreen></iframe>";
?>
<div class="videoitem">
<div class="videotitle">
<h3><?php echo $media->group->title; ?></h3>
<p><?php echo $media->group->description; ?></p>
</div>
</div>
<?php $i++; if($i==3) { echo '<div class="clear small_v_margin"></div>'; $i=0; } } ?>
Example
First, about the url. Note that this url means using version 2 and that this version has been deprecated. See "YouTube API Subject to the Deprecation Policy": https://developers.google.com/youtube/youtube-api-list
Note also, that by default version 1 is used and you may want to add: v=2, for version 2. If you prefer the response in JSON instead of XML, then add: alt=json. For better reading add: prettyprint=true.
For example:
https://gdata.youtube.com/feeds/api/users/estXcrew/uploads?maxresults=1&v=2&alt=json&prettyprint=true
Further, since JSON is used in api version 3, you may prefer JSON to be used. For using api version 3 it is necessary to obtain an api-key first, by registering.
To capture the response, you need to send the url to the server using XMLHttpRequest() or ActiveXObject().
Look for (JS or other type) code libraries that may help you, for example to parse and compose XML or JSON strings; or send url requests.
See for jSON parsing: Parse JSON in JavaScript?
About your code supplied: use parameters. For example, after getting a videoId:
<!DOCTYPE html>
<html>
<head>
<!--
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
// Adding a library to send requests to a server ?
</script>
-->
<script>
var myVideoId = "ZY7aRxb-Z1c"; // Set the videoId here.
// insert an iframe
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; // reference to the player object
var param = { // video-player parameters
height: '200',
width: '200',
videoId: 'xxxxxxxxxxx',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
};
param.videoId = myVideoId // Replace the videoId parameter
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', param); // create the player object
}
function onPlayerReady(event) {
event.target.playVideo(); // start to play
}
var done = false; // flag
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 6000); // This will stop playing after 6 seconds
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</head>
<body>
<div id="player">please wait...</div>
</body>
</html>

How do videos autoplay on iOS at youtube.com

When I set autoplay to true for a YouTube video (IFrame API) on my site, it doesn't work. All the documentation says apple disables autoplay on ios for bandwidth reasons.
However, I see that videos play automatically (without clicking on the video element) on youtube.com on iPad. How did YouTube make it work? It would be hard to imagine Apple does something special just for YouTube.
It seems that Youtube's team uses the interaction of the user when taps/clicks a video button to authorize the reproduction.
Remember that youtube.com is a SPA (Single Page Application) so there is no page reload or redirection.
So, youtube.com doesn't have autoplay enabled.
You can do it with javascript.
Here is an example:
<div class="video-container">
<div id="player"> </div> <!--<iframe width="960" height="720" src="//www.youtube.com/embed/5YptIh_avrM?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>-->
</div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '720',
width: '960',
videoId: 'YOUR_ID_HERE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
event.target.setVolume(20);
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
}
function stopVideo() {
player.stopVideo();
}
</script>
I stumbled into similar but more complicated issue/requirement.
I need to show YouTube video on a modal popup. Popup is shown on a click.
Have taken YouTube API code (From https://developers.google.com/youtube/iframe_api_reference) and modified a bit to work with Bootstrap popup.
Below is my code
<div class="modal" id="videoModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="videoWrapper">
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"> </div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'YOUR VIDEO ID',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
//event.target.playVideo();// Nullifying the action otherwise the video will play as soon as page loads
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
function ShowPopup() {
$('#videoModal').modal('show');
player.playVideo();
}
//Stop video when bootstrap popup is closed
$("#videoModal").on('hide.bs.modal', function () {
player.stopVideo();
});
</script>
It can't be done. For various reasons (including, but not limited to data usage), Apple doesn't allow auto-playing of videos.
Please refer to:
Youtube embedded video: autoplay feature not working in iphone
I haven't tested this, but you may be able to use Javascript and call the play function for the player, or even just click the element when the page has loaded.

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