I am embedding a Youtube video and using the YT JS API. The user is encouraged to use their Chromecast to view the embedded video. However, when the video is cast with the button in the player, player.getCurrentTime() and player.getPlayerState() become frozen, and the onStateChange event doesn't fire.
Is there anything I can do to work around these issues, or is this a problem only youtube can fix? Thanks!
My code:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
events:{
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event){
console.log('Player StateChange: '+event.data); //This never runs when casting a video.
}
Here's the code
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;
//execute as soon as the player API code downloads
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// execute when the onReady event fires
//starts video
function onPlayerReady(event) {
console.log("onPlayerReady");
console.log(event);
var duration = event.target.getDuration();
console.log("Duration:" + duration);
fillPlaybackRates();
}
// when the onStateChange event fires
function onPlayerStateChange(event) {
console.log("onPlayerStateChange")
console.log(event)
if (event.data == YT.PlayerState.PLAYING) {
console.log(YT);
}
}
var pause = $("#pause"),
start = $("#start"),
mute = $("#mute");
pause.on('click', function () {
player.pauseVideo();
});
start.on('click', function () {
player.playVideo();
});
var fillPlaybackRates = function () {
var playbackDropdownMenu = $(".dropdown-menu");
var playbackRates = player.getAvailablePlaybackRates();
console.log(playbackRates);
for (var i = 0; i < playbackRates.length; i++) {
playbackDropdownMenu.append('<li role="presentation"><a role="menuitem" tabindex="-1" href="#">' + playbackRates[i] + '</a></li>');
}
}
var playbackRatesButton = $("#playback-rates");
$(document).on('click','.dropdown-menu > li > a', function () {
var option = $(this).text();
playbackRatesButton.text(option);
player.setPlaybackRate(option);
});
Here's the full gist: iFrameYouTubeApi.html
You can also have a look here: Continuing with Chromecast: Embedding YouTube into Custom Receivers
Related
I am currently trying to trigger some functions, for when the embedded youtube player is being loaded, but for some reason is doesn't it seem like the API is being loaded, or the callback functions being triggered based on the API event states?
What am I doing wrong?
const $ = require('jquery');
$(document).ready( function() {
console.log( "ready!" );
loadPlayer();
});
function loadPlayer() {
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubePlayerAPIReady = function() {
onYouTubePlayer();
};
} else {
onYouTubePlayer();
}
}
var player;
function onYouTubePlayer() {
player = new YT.Player('player', {
height: '490',
width: '880',
videoId: 'video',
playerVars: { controls:1, showinfo: 0, rel: 0, showsearch: 0, iv_load_policy: 3 },
events: {
'onReady': window.onPlayerReadVar = function() {
onPlayerStateChange();
},
'onStateChange': window.onPlayerStateChangeVar = function() {
onPlayerStateChange();
}
}
});
console.log("youtubePlayerready")
}
var done = false;
function onPlayerStateChange(event) {
console.log("onPlayerStateChange");
done = true;
}
When the page loads I only see "ready" outputted in the console.. Nothing else?
What am I doing wrong here?
I am trying to change iframe source everytime user click on the skip button and it doesn't work.
var player;
window.onYouTubePlayerAPIReady = function() {
alert('called onYouTubePlayerAPIReady');
player = new YT.Player('header-video__video-element', {
events: {
'onStateChange': ShowMe
}
});
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function ShowMe() {
var sStatus;
sStatus = player.getPlayerState();
if (sStatus == -1) alert("Video has not started.");
else if (sStatus == 0) {
$('#ytplayer').replaceWith('<img class="special_hover" src="image" alt="" />')
}
else if (sStatus == 1) {
} //Video is playing
else if (sStatus == 2) {
}
else if (sStatus == 3) {
} //video is buffering
else if (sStatus == 5) {
} //Video is cued.
}
//CODE TRIGGERED BY BUTTON
$(this.settings.playTrigger).on('click', function(e) {
alert('changing source');
$("#header-video__video-element").attr('src', "https://www.youtube.com/watch?v=eozsR79JjPM");
//document.getElementById('header-video__video-element').setAttribute('src', "https://www.youtube.com/embed/eozsR79JjPM");
alert('changed');
//player.loadVideoById("95CX2VL0hVY");
// e.preventDefault();
// that.appendIframe();
});
The player.loadVideoById method that you commented out should do the work. Here is a working example of a little application I did
//Code from the YouTube iFrame API doc
//https://developers.google.com/youtube/iframe_api_reference
var player;
var id = "V13MbW3oMUw";
//Init API
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
height: '720',
width: '960',
videoId: "JxfzRNA2_8M",
events: {
'onReady': onPlayerReady,
}
});
};
// Launch video as it's ready
function onPlayerReady(event) {
event.target.playVideo();
}
//Change video onclick
$("#button").click(function(id){player.loadVideoById(id);});
I've been trying for a little while now to create an embedded YouTube player which will automatically start a playlist in shuffle when someone loads a page. A few searches led me to an alternative solution: Loading a new video with a random index in the playlist when the current one ends.
This is the code I currently have:
<div id="player"></div>
<button value="next" onclick="next();">Next</button>
<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: '390',
width: '640',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var oldNumber = 0;
var NewNumber = 0;
function newRandomNumber(min, max) {
oldNumber = NewNumber;
NewNumber = Math.floor(Math.random() * max) + min;
if (NewNumber == oldNumber) {
newRandomNumber(min, max);
} else {
return NewNumber;
}
}
function onPlayerReady(event) {
next();
}
function next() {
player.loadPlaylist({
'listType': 'playlist',
'list': 'PLxBKLJmrCEphpgRihb-H0QUColR_bFu6s',
'index': newRandomNumber(0, 139),
'startSeconds': '0',
'suggestedQuality': 'small'
});
player.setShuffle({
'shufflePlaylist': true
});
}
function onPlayerStateChange(event) {
if (event.data == 0) {
next();
}
}
</script>
With a bit of testing here and there it looks like this is the part which does not work correctly:
function onPlayerStateChange(event) {
if (event.data == 0) {
I've tried setting it to other integers and testing appropriately but it seems nothing will fire the event.
For what it's worth, the majority of the code was taken from here but I haven't been able to find any help on that page: Shuffle Playlist fix for Youtube API
Thanks.
If we set the random and playlist parameters while instantiating the Youtube player, the shuffle and events works. Here is the code displaying a working player:
<div id="player"></div>
<button value="next" onclick="next();">Next</button>
<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: '390',
width: '640',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
},
playerVars: {
'html5': 1,
'listType': 'playlist',
'list': 'PLxBKLJmrCEphpgRihb-H0QUColR_bFu6s',
'index': newRandomNumber(0, 139),
'startSeconds': '0',
'autoplay': 1,
'suggestedQuality': 'small'
}
});
}
var oldNumber = 0;
var NewNumber = 0;
function newRandomNumber(min, max) {
oldNumber = NewNumber;
NewNumber = Math.floor(Math.random() * max) + min;
if (NewNumber == oldNumber) {
newRandomNumber(min, max);
} else {
console.log(NewNumber);
return NewNumber;
}
}
function onPlayerReady(){
//nothing to do as of now.
}
function next() {
console.log('next called');
player.setShuffle({
'shufflePlaylist': true
});
}
function onPlayerStateChange(event) {
if (event.data == 0) {
next();
}
}
</script>
so i am trying to make a sort of youtube video request system. on my computer i have a file called video.txt with the id's of a few youtube videos in it. (each one gets their own line.) my code is as follows
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
function addToList(file)
{
var getVid = new XMLHttpRequest();
getVid.open("GET", file, false);
getVid.onreadystatechange = function ()
{
if(getVid.readyState === 4)
{
if(getVid.status === 200 || getVid.status == 0)
{
var allText = getVid.responseText;
returnText = allText.replace( /\n/g, " " ).split( " " );
vid.push.apply(vid, returnText);
console.log(vid[0]);
}
}
}
getVid.send(null);
}
//make the array
var vid = []
// create youtube player
setInterval( getVid , 500 );
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
player.loadVideoById({'videoId': 'qjlH7pQRK9I', 'startSeconds': 0});
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
addToList("video.txt");
if (vid[0] == "") {
vid.shift();
}
if (vid === undefined || vid.length == 0) {
vid.push("qjlH7pQRK9I");
player.loadVideoById({'videoId': vid[0], 'startSeconds': 0});
vid.shift();
} else {
player.cueVideoById( vid[0]);
player.playVideo();
vid.shift();
}
}
}
</script>
Oh yeah. and whenever there is no video it plays a 10 second video of nothing. and it always starts with that. but then after that ends the next video should pop up and start playing... but it doesnt. instead i get this
http://i.stack.imgur.com/DrhJl.png
but there are no errors in the console... i'm probably doing something dumb... but i would love some help <3
What's that setInterval doing there? Definitely remove that.
I also changed where the text file is read.
I think this is the idea.
What do you want as the first video? First 10 seconds of nothing, or not?
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// array containing IDs of youtube videos
var vid = [];
// youtube player object
var player;
//Loads a text file with youtube IDs, pushes them to an array ( var vid )
function loadIDsFromFile(file) {
var getVid = new XMLHttpRequest();
getVid.open("GET", file, false);
getVid.onreadystatechange = function () {
if(getVid.readyState === 4) {
if(getVid.status === 200 || getVid.status == 0) {
var allText = getVid.responseText;
returnText = allText.replace( /\n/g, " " ).split( " " );
vid.push.apply(vid, returnText);
console.log(vid[0]);
}
}
}
getVid.send(null);
}
// the Youtube API is ready to use. Let's load the text file here; no point in waiting
function onYouTubePlayerAPIReady() {
loadIDsFromFile("video.txt");
player = new YT.Player('player', {
height: '390',
width: '640',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
player.loadVideoById({'videoId': 'qjlH7pQRK9I', 'startSeconds': 0});
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) { // last video stopped playing, let's load a next one and play it
if (vid === undefined || vid.length == 0 || ! vid[0] ) {
vid=["qjlH7pQRK9I"]; //default, "10 seconds of nothing" video
}
player.cueVideoById(vid[0]);
player.playVideo();
vid.shift();
}
}
</script>
I'm trying to get document reloaded every 10 seconds when onStateChange has value YT.PlayerState.ENDED (0) or YT.PlayerState.CUED (5).
Document IS NOT meant to be reloaded if YT.PlayerState is something else than YT.PlayerState.ENDED (0) or YT.PlayerState.CUED (5).
The problem is that document gets reloaded even when YT.PlayerState is NOT ENDED (0) or CUED (5).
The code below displays random Metallica video from Youtube from the following list:
Metallica - Until it sleeps (Youtube video ID = F3WIHtOmkBg)
Metallica - The unforgiven (Youtube video ID = TUHFfR8hWcA)
Metallica - Nothing else matters (Youtube video ID = Tj75Arhq5ho)
I have found out that YT.PlayerState.PLAYING (1) is firing and 'Playing' gets logged to the console but it seems that "clearTimeout()" and "refresh = undefined" has no effect and thus document will be reloaded even when video is playing (has status YT.PlayerState.PLAYING (1)).
I have used YouTube Player API Reference for iframe Embeds as a reference.
At the moment my code is the following:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
// Youtube, F3WIHtOmkBg - Metallica - Until it sleeps
// Youtube, TUHFfR8hWcA - Metallica - The unforgiven
// Youtube, Tj75Arhq5ho - Metallica - Nothing else matters
var videoArray = [
'F3WIHtOmkBg',
'TUHFfR8hWcA',
'Tj75Arhq5ho'];
var randomIndex = Math.floor(Math.random() * videoArray.length);
var randomVideoId = videoArray[randomIndex];
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 refresh() { setTimeout(function() {
window.location = window.location.pathname;
player = new YT.Player('player', {
width: '550',
height: '331',
videoId: randomVideoId,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}, 10000);
}
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '550',
height: '331',
videoId: randomVideoId,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.stopVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
refresh();
console.log('Ended');
}
if (event.data == YT.PlayerState.PLAYING) {
clearTimeout();
refresh = undefined;
console.log('Playing');
}
if (event.data == YT.PlayerState.PAUSED) {
clearTimeout();
refresh = undefined;
console.log('Paused');
}
if (event.data == YT.PlayerState.BUFFERING) {
clearTimeout();
refresh = undefined;
console.log('Buffering');
}
if (event.data == YT.PlayerState.CUED) {
refresh();
console.log('Cued');
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</head>
<boby>
<div id="youtubetest">
<div id="player"></div>
</div>
<div id="currenttime">
<script>
var now = new Date();
var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate();
datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
document.write('Current time is: ' + now);
</script>
</div>
</html>