YouTube API - onPlayerStateChange - javascript

I'm using the YouTube API in conjunction with Cyclone Slider. The goal is to pause the slideshow once the YouTube starts playing. I'm using the following code which works nicely:
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
<script>
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('video', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if(event.data === 1) {
$(".cycle-slideshow").cycle('pause');
}
if(event.data === 2) {
$(".cycle-slideshow").cycle('resume');
}
}
</script>
However, it only seems to work if I do a refresh of the page. If I navigate between pages and return to the homepage, it will no longer work.
Any suggestions for why this is the case? I've tried a few suggestions I found on Google but couldn't get any to work. I'm a little lost on this one.
Any help would be greatly appreciated.

Try the following code, it works for me -
function loadYouTube(targetId){
ytplayer = new YT.Player(targetId, {
events: {
'onStateChange': function(event){
/** YouTube API
-1 (unstarted)
0 (ended)
1 (playing)
2 (paused)
3 (buffering)
5 (video cued)
**/
if (event.data == 1) {
//do your work here
}
console.log(event.data)
}
}
});
}

Related

Youtube Iframe Api not working on live website

I'm using youtube iframe API for redirecting users to another link when the video ends. I've an existing iframe on my webpage. So I've written the below code which works on my local environment but in the live website it doesn't work.
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;
window.onYouTubeIframeAPIReady = function () {
window.YT.ready(function () {
player = new window.YT.Player(element_id, {
events: {
'onStateChange': onPlayerStateChange
}
});
});
};
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
if (quiz_permalink) {
window.location.href = quiz_permalink;
} else if (next_lesson_permalink) {
window.location.href = next_lesson_permalink;
}
}
}
Can anyone guide me what can be the possible reason for this not working in the live website ?
Thanks in advance

Hard to resolve issue! :: TypeError: player.loadVideoById is not a function

When $('#myModal').on('show.bs.modal' gets called. I get this:
TypeError: player.loadVideoById is not a function. (In 'player.loadVideoById(x)', 'player.loadVideoById' is undefined)
https://jsfiddle.net/rdbj3ty1/5/
In JS Fiddle the code works, but when I add it to my code base, it stops working. I have a lot of other js code and CSS code that it must be interfering with. Is there a way to prevent the interference? Maybe wrap my js code with a block or add more specific references? Is namespacing the issue? If so, how do I do that?
I don't really know what to try. I have spent 2 days on this and getting nowhere.
JS
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',
videoId: 'novideoid',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
$('.open-popup').click(function() {
event.target.playVideo();
});
$('.close-popup').click(function(e) {
player.stopVideo();
});
}
// 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 === 0) {
$('.close.close-popup').click();
}
}
function stopVideo() {
player.stopVideo();
}
$(function () {
onYouTubeIframeAPIReady();
$('#myModal').on('show.bs.modal', function(e) {
var videoId = $(e.relatedTarget).data('video-id');
var x = new String(videoId);
player.loadVideoById(x);
});
});

Youtube SeekTo Suddenly stopped working - Looping video?

So from what I can gather one or two things are going from with my youtube video's either the seekTo function has stopped working or the hole API has....(Or youtube has changed something) Now please take in mind my codes were working flawlessly without fault untill yesterday... (code usually doesn't break over night).
Here are 2 sites with the SeekTo function that loops the video via PlayerState ENDED:
http://imvu.url.ph/aattpx/DC_MAR/Base/XML/COMPIC_X1/2014/LayDStroke/maintemp/index.html
http://imvu.url.ph/FTP/2013/System/Core/Int/Warning/Dont_Not_Touch/DKLAY2013BLUE/Layout/Infuriate/index.html
The codes for the youtube video are more or less identical so I'll just post 1 of the codes:
view-source:imvu.url.ph/aattpx/DC_MAR/Base/XML/COMPIC_X1/2014/LayDStroke/maintemp/video.html
<div id="youtube-fs"><iframe id="youtube-iframe" type="text/html" src="http://www.youtube.com/embed/o2cvRsiRkqs?enablejsapi=1&autoplay=1&showinfo=0&iv_load_policy=3&controls=0&rel=0&wmode=transparent&vq=hd720&hd=1&loop=1" frameborder="0" wmode="Opaque" ></iframe> <script type="text/javascript">
<!--
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
player.quality = 'hd720';
function onYouTubePlayerAPIReady() { player = new YT.Player('youtube-iframe', { events: { 'onStateChange': onPlayerStateChange } }); }
function onPlayerReady(event) { event.target.setPlaybackQuality('hd720'); event.target.playVideo(); }
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd720');
}
if (event.data == YT.PlayerState.ENDED) { player.seekTo(0, true); } // end if
}
-->
</script>
</div>
</div></div>

youtube reference api for iFrame embeds is not loading iFrame

I have used the code refering https://developers.google.com/youtube/iframe_api_reference#Getting_Started. I have copied the same code as provided in above url. But, it gives me a blank page.
<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>
Can anyone please help me to resolve this issue?
This code seems good. What did you paste it in? Maybe it's an unrelated syntax error...

YouTube API playlist shuffle not working?

I have been trying to set-up my youtube api to shuffle my playlist but the order is the same all the time...
Here is the link where I am getting my code from
https://developers.google.com/youtube/iframe_api_reference#setShuffle
Am I calling it right?
here is my code below
<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: '390',
width: '640',
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
player.loadPlaylist({'listType': 'playlist', 'list': 'PLF776D41D8211F340','index': '0','startSeconds': '0','suggestedQuality': 'hd720'});
player.setShuffle({'shufflePlaylist' : 1});
}
</script>
I have tried setting shufflePlaylist to 'true', I have tried cueplaylist instead of loadplaylist and I have even tried putting the shufflePlaylist in the load Playlist...nothing is getting shuffled.
I have looked into this and I see that it was an issue with the API, but that was 2 years ago, is there a solution to this issue?
Below is what I have tried and didn't work
player.setShuffle(1);
player.setShuffle('1');
player.setShuffle(true);
player.setShuffle('true');
player.setShuffle({'shufflePlaylist' : true});
player.setShuffle({'shufflePlaylist' : 1});
player.setShuffle({'shufflePlaylist' : 'true'});
player.setShuffle({'shufflePlaylist' : '1'});
I have also tried copying and example from here....https://developers.google.com/youtube/youtube_player_demo
The Shuffle works here after u load the playlist and click a button.
This is a known bug that is yet to be fixed - see this post
A work around however is to pass a random number to playVideoAt, as follows:
var getRandom = function(min, max) {
return Math.random() * (max - min) + min;
};
var playRandomTrack = function() {
num = getRandom(0, 99);
player.playVideoAt(num);
};
I found the solution. You have to load the player.setShuffle(true) just after the first video starts:
function onPlayerReady(event) {
event.target.playVideo();
setTimeout(setShuffleFunction, 1000);
}
function setShuffleFunction(){
player.setShuffle(true);
}
Demo on my online music tv website
More or less the same solution as Ivan's. Works for me!
function onPlayerReady(event) {
event.target.mute();
setTimeout( function() {
event.target.setShuffle(true);
event.target.setLoop(true);
}, 2000);
}
If you launch it directly, it will definitely not work (I have noticed, to my frustration).
Try the following:
function onPlayerStateChange(event) {
if(event.data === 0) {
player.setShuffle(true);
player.playVideo();
}
}

Categories