How to Dynamically update Youtube Player videoID - javascript

I have a js function that returns a random VideoID from a channel. I want to dynamically insert this ID into the youtubeAPI's videoID parameter.
// 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: <<INSERT RETURN OF FUNCTION HERE>>
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}

Prueba utilizando esta linea :)
player.loadVideoById("id_video");

Related

Autostart a youtube video from Javascript

I am trying to automatically start a youtube video when it loads and when it finishes I want it to alert that it's done.
This is my HTML/JS
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
The part that alerts when the video is done is working but the auto-player doesn't. I HAVE TRIED TO PUT THE ?AUTOPLAY=1 TAG AFTER THE VIDEO URL BUT THAT DOESN'T SEEM TO WORK EITHER!
I have seen all the variations to this question and tried all the anwsers but none of them work.
Does anyone have any idea on what I should try next?
Thanks to cat my problem is solved!
All I had to do is go to chrome://flags/#autoplay-policy and select "No user gesture is required" in the dropdown menu under the "Autoplay policy" and then relaunch chrome.
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
autoplay: 1,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}

Youtube iFrame API how do I invoke IframeAPIReady function after getting list of videos

I am making simple Youtube Video Player myself, and I'd like to know how to invoke onYouTubeIframeAPIReady() after I get a list of videos.
What I like to do is display the first video in list as initial video.
In my html somewhere:
<script src="//www.youtube.com/iframe_api"></script>
This is initial iframe embed code from official sample code:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player-box', {
// height: '390',
// width: '640',
videoId: {FIRST_VIDEO_ID},
events: {
'onReady': onPlayerReady,
// 'onStateChange': onPlayerStateChange
}
});
}
Here is how I get a list of vids:
$.getJSON(
'https://www.googleapis.com/youtube/v3/videos',
{
part: 'snippet',
id: {VIDEO_IDs},
key: {MY_API_KEY},
},
function(data) {
var items = data.items;
console.log(data);
// cannot put onYouTubeIframeAPIReady here...
}
);
I guess I cannot put onYouTubeIframeAPIReady() as $.getJSON's callback, since it is called outside the script.
I kinda solve this problem myself.
I wrapped everything inside var onYouTubeIframeAPIReady = function() {...
Here's how I done:
var onYouTubeIframeAPIReady = function() {
var videos = '{VIDEO_ID1}, {VIDEO_ID2}, {VIDEO_ID3}';
$.getJSON(
'https://www.googleapis.com/youtube/v3/videos',
{
part: 'snippet',
id: videos,
key: {MY_API_KEY},
},
function(data) {
var items = data.items;
console.log(items);
$.each(items, function(i, video){
console.log(video);
});
var player;
player = new YT.Player('player-box', {
// height: '390',
// width: '640',
videoId: {INITIAL_VIDEO_ID},
events: {
'onReady': onPlayerReady,
// 'onStateChange': onPlayerStateChange
}
});
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
// console.log(event.data);
// if (event.data == YT.PlayerState.PLAYING && !done) {
// everytime change vids playing for 6secs then stop
if (event.data == YT.PlayerState.PLAYING) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
}//$.getJSON callback
}

Javascript doesn't work on ajax post

I'm using Youtube Iframe API and using their script the player loads fine. But when I do an ajax call to the php file containing javascript code to run the player, it doesn't execute.
function get_content(song_id,url,song_title) {
if (song_id == null)
return;
document.title = song_title + browser_title_suffix;
$.get('/ajax/player.php',{song_id:song_id}, function(data) {
$('#main_content').html(data).css({'opacity':0}).animate({'opacity':1});
});
}
/ajax/player.php contains this code - https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player
However, the player does not again. I even tried player.remove() but that didn't help either.
UPDATE 1:
My PHP file:
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
$(document).ready(function(){
get_content('.$row[song_id].',null,"'.$row[title].'");
});
</script>
My javascript file:
function get_content(song_id,url,song_title) {
if (song_id != null) {
$.get('/ajax/player.php',{song_id:song_id}, function(data) {
video_id = data;
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: video_id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
}
}
However, the video player does not load.
You can't get javascript via ajax and then run the just recieved javascript. What you want to do is just send the youtube video id via ajax and then use a function like this to place the player:
function get_content(song_id,url,song_title) {
if (song_id != null) {
$.get('/ajax/player.php',{song_id:song_id}, function(data) {
video_id = data;
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: video_id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
}
}
Better yet, try JSON to send and recieve data via Jquery.

how to display lightbox after Video Play Finishes?

I have a youtube video.
I want to show a lightbox when it stops playing. I need this to be done using javascript/jQuery or PHP. Ajax is also fine.
I looked for a solution but didn't find one that worked.
If you can use youtube api then, something like this should work:
<script type="text/javascript">
$(document).ready(function() {
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'YmHAAqOsBqA',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if(event.data === 0) {
//completed playing
//open lightbox
$('#yourElementId a').lightBox();
}
}
});
</script>
Did you mean something like this.
Hope it helps

Example YouTube Playlist Code?

I'd like to create a playlist that loads all the videos a specific user has uploaded.
I was suggested to use the following code (assuming the account to pull in is YouTube):
loadPlaylist( { listType: 'user_uploads', list: 'youtube' } );
I have looked over the API pages as well: http://code.google.com/apis/youtube/js_api_reference.html
But I can't find an actual example code that uses load playlist. Being completely new to YouTube API I have no idea what type of wrapper code I need to make the above work. Something like this (of course I'm missing parts):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
loadPlaylist( { listType: 'user_uploads', list: 'youtube' } );
</script>
Or if someone could provide working example with the original loadplaylist line that would be great, and I can work on the other details I need on my own from there.
-YouTube API Newbie
First of all , I suggest you to use IFRAME embed style, because it work on both desktop and mobile (iOS,Android,BB,Windows, very nice). The sample code is at Youtube IFRAME embed . This one contain the html code for you to get started.
Let's get into your question.
1 Let assume you get youtube player as
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady
}
});
don't care with videoId. just insert any valid youtube video's ID.
notice that we register 'onReady': onPlayerReady
2 Load your playlist into the player using onPlayerReady
function onPlayerReady(event) {
event.target.loadPlaylist({list: "UUPW9TMt0le6orPKdDwLR93w", index: 1, startSeconds: 10,suggestedQuality: "small"});
}
You can read more on Youtube JSAPI reference
Hope this work on you. ^^.
UPDATE
you can also specify the playlist in playerVars object.
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
playerVars: {
listType:'playlist',
list: 'UUPW9TMt0le6orPKdDwLR93w'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
it has the feature
-make playlist of video id.
-to play next and previous.
-play,pause and stop
https://jsfiddle.net/Physcocybernatics/6dkw8e7r/
<div id="player"></div>
<div class="buttons">
<button class="button" id="play-button">PLAY</button>
<button class="button" id="pause-button">PAUSE</button>
<button class="button" id="previous">previous</button>
<button class="button" id="next">Next</button>
<button class="button" id="stop-button">STOP</button>
</div>
/**
* Put your video IDs in this array
*/
var videoIDs = [
'kJQP7kiw5Fk',
'2cv2ueYnKjg',
'nfs8NYg7yQM',
'ClU3fctbGls'
];
var player, currentVideoId = 0;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
playerVars: {
controls: 1,
showinfo: 0,
rel: 0,
showsearch: 0,
iv_load_policy: 3
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.loadVideoById(videoIDs[currentVideoId]);
// bind events
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function() {
player.playVideo();
});
var pauseButton = document.getElementById("pause-button");
pauseButton.addEventListener("click", function() {
player.pauseVideo();
});
var stopButton = document.getElementById("stop-button");
stopButton.addEventListener("click", function() {
player.stopVideo();
});
var next = document.getElementById("next");
next.addEventListener("click", function() {
player.nextVideo();
});
var pre = document.getElementById("previous");
pre.addEventListener("click", function() {
player.previousVideo();
});
player.loadPlaylist( {
playlist:videoIDs
} );
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
currentVideoId++;
if (currentVideoId < videoIDs.length) {
player.loadVideoById(videoIDs[currentVideoId]);
}
}
}

Categories