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>
Related
I want to have a play / pause toggle button that controls my youtube video.
<a id="play-button">Play / Pause</a>
Right now it is just a link. This is the javascript code for the onPlayerReady function
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function(event) {
if (event.data==YT.PlayerState.PLAYING) {
player.pauseVideo();
}else {
player.playVideo();
}
});
For some reason when I click the link it always does the else command. How can I get it to recognize that the video is currently playing? Is there a better way to do this play / pause toggle action?
SOLUTION for onPlayerStateChange
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd1080');
}
if (event.data == YT.PlayerState.PAUSED) {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
this.is_playing = false;
}
if (event.data == YT.PlayerState.PLAYING) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
this.is_playing = true;
}
}
FULL CODE
<div id="centerplayer">
<div id="player"></div>
<script>
var is_playing = false;
var fullscreen = false;
var live = true;
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 onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '600',
width: '1067',
playerVars:{
autoplay: 1,
controls: 0,
rel: 0,
iv_load_policy: 3,
showinfo: 0
},
loadPlaylist:{
listType:'playlist'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': onErrorDetect
}
});
}
function onErrorDetect(event){
if (event.data == 100) {
//video request was not found, error occurs when video has been removed or has been marked as private
event.target.nextVideo();
} else{
location.reload();
}
}
function onPlayerReady(event) {
event.target.setPlaybackQuality('default');
event.target.loadPlaylist(gon.playlist,gon.s_index,gon.s_time);
event.target.setLoop(true);
//PLAYER CONTROLS
var playButton = document.getElementById("play-button");
var that = this;
playButton.addEventListener("click", function(click_event) {
if (that.is_playing) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
// if(live){
// var liveimg = document.getElementById('live-icon');
// liveimg.parentNode.removeChild(liveimg);
// live = false;
// }
player.pauseVideo();
}else {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
player.playVideo();
}
});
var muteButton = document.getElementById("mute-button");
muteButton.addEventListener("click", function() {
if(player.isMuted()){
$("#mute-button").attr("src", "http://www.beached.tv/assets/sound-2850c52028b16dd2c2e264c5dddb39ba.svg");
player.unMute();
}else{
$("#mute-button").attr("src", "http://www.beached.tv/assets/mute-8d50674fdbcdd2cc9597f009be41cea9.svg");
player.mute();
}
});
var enlargeButton = document.getElementById("enlarge-button");
enlargeButton.addEventListener("click", function() {
if (fullscreen){
$("#enlarge-button").attr("src", "http://www.beached.tv/assets/resize-enlarge-a44a4204dca596b45aacb25610ee3189.svg");
player.setSize(1067,600);
fullscreen = false;
}else{
$("#enlarge-button").attr("src", "http://www.beached.tv/assets/resize-shrink-f63cf0e6ab1eb2bb8f7223798c4fc9c5.svg");
player.setSize(1410,793);
fullscreen = true;
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd1080');
}
if (event.data == YT.PlayerState.PAUSED) {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
this.is_playing = false;
if(live){
var liveimg = document.getElementById('live-icon');
liveimg.parentNode.removeChild(liveimg);
live = false;
}
}
if (event.data == YT.PlayerState.PLAYING) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
this.is_playing = true;
var current_time = Math.round(new Date().getTime() / 1000);
if (current_time > gon.end_of_stream){
// location.reload();
}
}
}
</script>
onPlayerReady parameter event isn't accessible, because the function you are passing to your addEventListener is also using that variable name
So use another variable name, ex:
playButton.addEventListener("click", function(click_event) {
There's actually a bigger error. You want to use onPlayerStateChange's event to tell the you the state. Here's a working snippet:
var is_playing = false;
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
var that = this;
playButton.addEventListener("click", function(click_event) {
if (that.is_playing) {
player.pauseVideo();
}else {
player.playVideo();
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
this.is_playing = true;
}
}
For the current HTML5 player of youtube you can do this easily using:
document.getElementByTagName('video')[0].play()
document.getElementByTagName('video')[0].play()
I created a chrome extension 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 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