Init YouTube iframe player without video ID - youtube-api

Is there a way to init YouTube iframe player without actualy loading video itself?
If do not provide videoId video is not loaded (no errors is shown) and player instance remains in "ready" state.
ytPlayer = new YT.Player('video-player', {
height: '100%',
width: '100%',
videoId: 'video-id-goes-here',
playerVars: {
.....
.....
Thanks for answer!

Sure, if you want to, the following code does work:
<script>
function onYouTubePlayerAPIReady() {
var player = new YT.Player('player', {
events: {
onReady: function() {
player.loadVideoById('sOEAD-gfJ_M');
}
}
});
}
</script>
<script src="//www.youtube.com/player_api" type="text/javascript"></script>
Alternatively, if you know you're going to be loading a playlist, you can leave out videoId and put in
playerVars: {
list: 'PLAYLIST_ID'
}
But while both of those approaches do work, what are you trying to accomplish? There might be a better way of doing it than initializing a YT.Player without the videoId.

Related

I have a YouTube video that when it finishes I would like to redirect to another page on my website

I have the video playing correctly, and there are several answers to my question on here but I can't for the life of me figure out where to append any of the solutions into my working code below
<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '700',
width: '1600',
videoId: 'MyVideo',
playerVars: { 'autoplay': 1, 'controls': 0,'modestbranding': 1, 'rel': 0 }
});
}
</script>
Certainly would appreciate any help!
You can use the players onStateChange event to call a function of your own.
For Example
function VideoEnd(state){
if(state.data === 0){
window.location="https://jsfiddle.net";
}
}
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '300',
width: '400',
videoId: 'kvKLpJbIfn4',
playerVars: { 'autoplay': 1, 'controls': 0,'modestbranding': 1, 'rel': 0 },
events:{
'onStateChange': VideoEnd
}
});
}
Here is a JsFiddle Example
If you have any questions please leave a comment below and I well get back to you as soon as possible.
I hope this helps. Happy coding!

embed and loop just a part of a youtube video (html5)

Is there a way to loop just a part of a YouTube video with the HTML5 player? I tried this code (start 7 sec, end 12sec)
The first "loop" shows the part I want, second and other loops shows the whole video.
It is working in Flash but I have issues in HTML 5 for mobile devices.
Here is my embed code:
<iframe allowfullscreen="" frameborder="0" width="960" height="720" src="http://www.youtube.com/embed/Bpu0TIXzI1w?version=3&start=7&end=12&autohide=1&hl=en_US&rel=0&loop=0&modestbranding=1&playlist=Bpu0TIXzI1w"></iframe>
You may need to use the Javascript API. It's a bit more complex, but you have full control over the video playback.
Documentation: https://developers.google.com/youtube/iframe_api_reference
Working example: http://jsfiddle.net/pbosakov/Lo6gwtff/
Code:
<div id="player"></div>
<script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>
<script type="text/javascript">
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'Bpu0TIXzI1w',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
loopStart();
player.playVideo();
}
function loopStart() {
player.seekTo(7); // Start at 7 seconds
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
setTimeout(loopStart, 5000); // After 5 seconds, restart the loop
}
}
</script>

Chromecast + Youtube embed + HTML5 video tag = bug

I have been trying to play two videos (not necessarily simultaneously) on a Chromecast app. Once of them is embedded via the Youtube API and the other is a standard HTML5 video loaded via the tag.
It turns out that the Youtube video simply won't be played back on Chromecast if I also have a standard tag in my HTML5 page. But if I remove that video tag, then the Youtube video will play back nicely.
Any advice is highly appreciated!
Only one active video stream is supported on Chromecast.
I ran into this same problem.
The key elements to solve it are, unload the cast player and don't let a video tag linger in the DOM with a SRC attribute set when you attempt to play Youtube.
As for YouTube, dont let the IFRAME that contains their video player linger in the DOM either when attempting to use the HTML5 video tag.
You'll need to tear down the previous player before attempting to trigger playback through the opposing mechanism.
Here is my sample receiver I used to troubleshoot and solve the problem. This is a working example.
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #000;
overflow: hidden;
}
</style>
</head>
<body>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="//www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver.js"></script>
<script type="text/javascript" src="//www.gstatic.com/cast/sdk/libs/mediaplayer/1.0.0/media_player.js"></script>
<video id="chromecast" style="width: 50%; height: 50%;"></video>
<script>
var ytCode = 'sSwLhYhYgI0'
var hlsUrl = 'http://host.com/playlist.m3u8'
</script>
<!-- Chromecast -->
<script type="text/javascript">
var castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
var messageBus = castReceiverManager.getCastMessageBus('urn:x-cast:tv.domain');
cast.receiver.logger.setLevelValue(cast.receiver.LoggerLevel.DEBUG);
cast.player.api.setLoggerLevel(cast.player.api.LoggerLevel.DEBUG);
castReceiverManager.onReady = function() {
console.info('[castReceiverManager.onReady]');
castReceiverManager.setApplicationState('Ready');
};
castReceiverManager.onSenderConnected = function(sender) {
console.info('[castReceiverManager.onSenderConnected]', sender.userAgent);
};
messageBus.onMessage = function(event) {
var message = JSON.parse(event.data);
console.info('[messageBus.onMessage]', message);
};
// Normal
castReceiverManager.start({
maxInactivity: 8,
statusText: 'Ready to play',
dialData: undefined
});
window.playDirect = function(id) {
// Tear down any YT player
$('#youtube').remove();
if(!id) id = 'chromecast';
var mediaElement = document.getElementById(id);
window.host = new cast.player.api.Host({'mediaElement':mediaElement, 'url':hlsUrl});
window.host.onError = function(errorCode) {
console.log('ERROR ' + errorCode);
};
var protocol = cast.player.api.CreateHlsStreamingProtocol(window.host);
window.CCplayer = new cast.player.api.Player(window.host);
window.CCplayer.load(protocol, 25);
setTimeout(function() {
mediaElement.play();
}, 1000);
};
</script>
<!-- Youtube -->
<script>
window.onYouTubeIframeAPIReady = function() {
console.log('Initialized Youtube');
};
var playYT = function() {
// Tear down any direct player
if(window.CCplayer) {
window.CCplayer.unload();
}
$('video').attr('src', '');
// Inject div tag that will be converted to iframe with player
$('body').append('<div id="youtube" style="width: 50%; height: 50%;"></div>');
window.YTPlayer = new YT.Player(
'youtube',
{
height: '100%',
width: '100%',
playerVars: {
'autoplay': 0,
'controls': 0,
'cc_load_policy': 0,
'fs': 0,
'iv_load_policy': 0,
'modestbranding': 0,
'rel': 0,
'showinfo': 0,
'enablejsapi': 1
},
events: {
'onReady': function() {
var params = { videoId: ytCode, startSeconds: 170 };
window.YTPlayer.cueVideoById(params);
window.YTPlayer.playVideo();
},
'onError': function(err) {
console.log('YT Error ' + err);
}
}
});
};
var iframeScript = document.createElement('script');
iframeScript.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(iframeScript, firstScriptTag);
</script>
</body>
</html>
Test:
Load up the sample receiver above, and alternate the following inside the chrome debug console:
playDirect()
or
playYT()

Youtube player controls & autohide not working

So I added the youtube iframe api to my website and followed the instructions; so this is my code:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
controls: '0',
autohide: '1',
videoId: 'I'd rather not display that',
events: {
// 'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Setting controls to 0 should not display the player's controls as per this article but it's still showing;
Also setting the autohide to 1 should have the progress bar and controls slide out after a couple of seconds as per this article but that also doesn't work.
Am I doing something wrong?
I got the embed version and the iframe version both autoplaying, autohide (don't really need) and hiding controls. I used the sample code and added in the parameters you needed.
All you need to do is replace your movie id and I think you will be up and running.
Here is the jsfiddle links where you can see it work and grab the code.
Embeded version: http://jsfiddle.net/franktudor/jk9SS/
<object width="640" height="390">
<param name="movie"
value="https://www.youtube.com/v/M7lc1UVf-VE?version=3&autoplay=1&autohide=1&controls=0"></param>
<param name="allowScriptAccess" value="always"></param>
<embed src="https://www.youtube.com/v/M7lc1UVf-VE?version=3&autoplay=1&autohide=1&controls=0"
type="application/x-shockwave-flash"
allowscriptaccess="always"
width="640" height="390"></embed>
</object>
Here is the iFrame version: http://jsfiddle.net/franktudor/2wh8T/
<iframe id="ytplayer"
type="text/html"
width="640"
height="390"
src="http://www.youtube.com/embed/M7lc1UVf-VE?autoplay=1&autohide=1&controls=0"
frameborder="0"/>
Both are options you can use. You are working with the iFrame version...I also recommend that version. But in the event you need another solution the embed version can be used.
Its not that script style but you can use a wrapper if needed.
Here is a link to an HTML5 youtube (and vimeo) video wrapper.
Ok, here is the functional code like your example that I got working: http://jsfiddle.net/franktudor/DU57E/
<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',
playerVars: { 'autoplay': 1, 'controls': 0 }, //this is what you need...
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>
Just set the variables inside the propertie 'playerVars'.

How make fancybox auto close when youtube video id done?

How i can make fancybox auto close when youtube video ended?
This isn't as simple as it sounds:
First determine if you are going to use the embed or iframe player.
Follow the embed player API or iframe player API examples to initialize the API.
Use the "onComplete" fancybox callback functon to set up the player once the popup is open.
In the callback, make sure you add an onStateChange event listener so you can determine when the video has completed (the value of zero means the video has ended)
Once you find that the video has ended, then use the $.fancybox.close method to close the popup
or, you could just let the user close the popup.
this is the full script with Fancybox-Youtube-Cookie-Autoclose-Autopopup just download the images that required in css put them in /fancybox folder in your root and replace with your video id. Really works fully tested...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/helpers/jquery.fancybox-media.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" media="screen" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script src="http://www.youtube.com/player_api"></script>
<script type="text/javascript">
// detect mobile devices features
var isTouchSupported = 'ontouchstart' in window,
isTouchSupportedIE10 = navigator.userAgent.match(/Touch/i) != null;
function onPlayerReady(event) {
if (!(isTouchSupported || isTouchSupportedIE10)) {
// this is NOT a mobile device so autoplay
event.target.playVideo();
}
}
function onPlayerStateChange(event) {
if (event.data === 0) {
$.fancybox.close();
}
}
function onYouTubePlayerAPIReady() {
$(function() {
if ($.cookie('welcome_video')) {
// it hasn't been three days yet
} else {
// set cookie to expire in 3 days
$.cookie('welcome_video', 'true', { expires: 3});
$(document).ready(function () {
$.fancybox.open({
href: "https://www.youtube.com/embed/qm1RjPM9E-g", /*YOUR VIDEO ID*/
helpers: {
media: {
youtube: {
params: {
autoplay: 1,
rel: 0,
// controls: 0,
showinfo: 0,
autohide: 1,
}
}
},
buttons: {}
},
beforeShow: function () {
var id = $.fancybox.inner.find('iframe').attr('id');
var player = new YT.Player(id, {
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
}); // fancybox
}); // ready
} // cookie else ready
}); // function for cookie
} // youtube API ready
</script>
After looking around without any luck here is a solution I came up with
See what we do, watch a video here
<div style="display: none;">
<div id="player"></div>
</div>
<script src="http://www.youtube.com/player_api"></script>
<script>
$(document).ready(function () {
$("a.video_button").fancybox({
'titlePosition' : 'inside',
'transitionIn' : 'none',
'transitionOut' : 'none'
});
});
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 's19V_6Ay4No',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
$(document).ready(function () { parent.$.fancybox.close();});
}
}
</script>
Yes this is the right way to handle to fancybox or colorbox. Youtube Video API provides different states to handle this like unstarted=-1, ended=0, playing=1, paused=2, buffering=3, video cued=5
Getting or traping this state in fancybox jquery code block one can achieve this easily. Just visit this article with proper demo also.Visit here

Resources