So I'm sticking a background video into our webpage, and I have the following code:
function setupYoutubeBG(videoId){
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// , This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
window.onYouTubePlayerAPIReady = function() {
player = new YT.Player('bgPlayer', {
playerVars: { 'autoplay': 1, 'controls': 0,'autohide':1, 'wmode':'opaque', 'playlist':videoId, 'loop':1 },
videoId: videoId,
events: {
'onReady': onPlayerReady}
});
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
}
}
Which is pretty straightforward, pulled right from the documentation. Works fine in all browsers including IE11 but for some reason, when testing in IE9 the video doesn't loop. I've set the playlist to the videoId, and like I said, it works everywhere else. If anybody has an idea or can point me in the right direction, it would be appreciated.
Related
I want to autoplay videos that are muted on my website. I found some code which seemed to work, but it doesn't. Why doesn't this javascript and HTML code work?
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_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 onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
playerVars: { 'autoplay': 1, 'controls': 1,'autohide':1,'wmode':'opaque' },
videoId: 'RDfjXj5EGqI',
events: {
'onReady': onPlayerReady}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
} </script>
jsFiddle for testing: https://jsfiddle.net/qswpr8tL/
Thanks!
Please build your onReady handler just like that:
var player;
// ...
function onPlayerReady(event) {
player.mute();
}
According documentation you have to call mute method on player object.
I'm trying to make a video that autoplays and witha perfect as I use it as a background for my landing page.
I can achieve perfect looping with HTML5 <video> tag as it caches the video upon download.
I don't want to host the video on my server, so I switched to embedding using YouTube IFrame API, I got everything to work correctly except that YT does not cache the video so there is a few seconds lag with every loop.
Is there any way to achieve a perfect loop playback using YouTube API without refresh?
Here's my code
Codepen
<div id="js-video"></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('js-video', {
height: '315',
width: '560',
videoId: 'CFgqg5B924U',
playerVars: {
'rel': 0,
'showinfo': 0,
'autoplay': 1, 'loop': 1,
'controls': 0,
'playlist': 'CFgqg5B924U'
},
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
</script>
Have you tried, instead of setting loop, set up an setInterval inside the onPlayerReady function, for example every 250 ms.. do a simple condition inside the setInterval, like:
if(vidplayer.getCurrentTime() > vidplayer.getDuration()-500){
//if video is 500 ms before ending, do
vidplayer.seekTo(0);
//gets back to the start of video
}
Following Code will play a perfect loop without buffering the video everytime.
<script>
// 1. 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);
// 2. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var restart_before = 500;//milisecenods
var code_overhead=10;
var player;
var total_video_time;
function onYouTubeIframeAPIReady() {
player = new YT.Player('video-foreground', {
height: '100%',
width: '100%',
playerVars: {
rel:0,
autoplay: 1,
controls: 0,
showinfo: 0,
autohide: 1,
modestbranding: 1,
vq: 'hd1080'},
videoId: '<?php echo $youtubevideoid;?>',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 3. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
player.mute();
total_video_time = (player.getDuration()*1000)-restart_before;
setTimeout(checkvideopos, total_video_time);
}
var done = false;
function onPlayerStateChange(event) {
// player.seekTo(0);
}
function checkvideopos()
{
// console.log("MIA\n");
var curr_time = player.getCurrentTime();
curr_time = curr_time * 1000;
if(curr_time>=total_video_time)
{
player.seekTo(0);
setTimeout(checkvideopos, total_video_time);
}
else
{
var new_time = (total_video_time - curr_time) - code_overhead;
setTimeout(checkvideopos, new_time);
}
}
</script>
I'm experimenting with the Youtube player but I can't get it to mute by default.
function onPlayerReady() {
player.playVideo();
// Mute?!
player.mute();
player.setVolume(0);
}
How do I mute it from the start?
Fiddle
Update:
JavaScript Player API is deprecated.
Use iframe Embeds instead.
Turns out player.mute() works fine. It only needed the parameter enablejsapi=1. Initial test in the fiddle didn't work because the player initiation had an error. The following works.
HTML:
<iframe id="ytplayer" type="text/html" src="https://www.youtube-nocookie.com/embed/zJ7hUvU-d2Q?rel=0&enablejsapi=1&autoplay=1&controls=0&showinfo=0&loop=1&iv_load_policy=3" frameborder="0" allowfullscreen></iframe>
JS:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
player.mute();
player.playVideo();
}
Fiddle
Credit to Gagandeep Singh and Anton King for pointing to enablejsapi=1
All above answers didn't work for me for some reason. It might be weird wordpress theme that I had to use or depreciated methods at Youtube API, I'm not sure. The only way of muting the player was to insert the code below into tag.
// Loads 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);
// Replaces the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'YOUR_VIDEO_ID',
playerVars: {
autoplay: 1,
controls: 1,
disablekb: 1,
hl: 'ru-ru',
loop: 1,
modestbranding: 1,
showinfo: 0,
autohide: 1,
color: 'white',
iv_load_policy: 3,
theme: 'light',
rel: 0
},
events: {
'onReady': onPlayerReady,
}
});
}
function onPlayerReady(event){
player.mute();
}
<div id="ytplayer"></div>
It's important to note that YouTube API mandates you run this within your markup directly within a <script> tag, or via a standard document.onLoad() native listener and not as a named function.
Otherwise it will not natively bind the onYouTubeIframeAPIReady() function to the DOM.
Try below code
var youtubeplayer = iframe.getElementById('ytplayer');
youtubeplayer .setVolume(0);
And below is your fiddle updated version,
NOTE: Must include enablejsapi=1 in video url
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
player.playVideo();
// Mute?!
//player.mute(); instead of this use below
event.target.mute();
//player.setVolume(0);
}
DEMO
Hope this helps...
So I figured I would update this with a working example. I have ditched stating the iframe tag and just used the iframe api to create an iframe and then loaded the player by id with a data attribute. Here is a working example below. So now all statechanges are passed consistently through the youtube player. So the script will load an iframe into the Div #player and you can just loadVideoByID pretty easily with jquery and javascript.
<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', {
playerVars: { 'autoplay': 0,},
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
alert('started');
}
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
$( document ).on( "click", ".video-link", function(e) {
e.preventDefault();
var videoID = $(this).attr('data-videoID');
player.loadVideoById(videoID);
});
</script>
And then use a link with a data-attribute like so.
Link
Rather than having buttons to play, why not cue to playlist when the player is ready? You can hold the video ID's in an array... If this isn't what you're looking for just leave a comment below and I will change things the best I can to fit.
//Array of videos
var MyVideos=["E6RGMRamAFk","IHQr0HCIN2w","CogIXrea6A4"];
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', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
//Player is ready, cue the array of videos into the playlist.
player.cuePlaylist(MyVideos);
}
function onPlayerStateChange(event) {
}
JS Fiddle - Working Demo
YouTube JavaScript Player API Reference
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!
I need to load the youtube iframe player with api on a jquery change event but it only shows how to load it when the script is loaded.
This is the script they use to load the player with the api.
var tag = document.createElement('script');
tag.src = "//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: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
I need to wait to fire this until my change event is fired so inside this..
$(document).on("change","#yt-url", function() {
youtubeUrl = $(this).val();
youtubeId = youtube_parser(youtubeUrl);
// Load the youtube player with api
});
What's the correct way to do this?
I think you'd just need to encapsulate the code creating the player into a function, which is called only by given event
$(document).on("change","#yt-url", function() {
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
});
Dmitry's example works, but I've got two modifications. First, check to see if the API is already loaded (whether YT.Player is defined) and only load the API if it isn't. Second, you might as well use $.getScript() since you mentioned you're using jQuery.
There's an example of this approach at https://code.google.com/p/youtube-direct-lite/source/browse/static/js/ytdl/player.js