To my problem, I have one link . I want to play the video by clicking the link in a fancybox overlay window. This is not a problem. The problem is the parameters, for example "autoplay" or "autohide".
The following link doesn't work:
The Overlay-Window opened, but the video is not playing automatically.
EDIT: I want to use the HTML5 Player on mobile devices. On a desktop-browser it works with the parameters, but not on mobile devices.
As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.
See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512
Have a look on code below.
Tested and found working on Mobile and Tablet devices.
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<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>
The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
</head>
<body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<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', {
width: '100%',
videoId: 'osz5tVY97dQ',
playerVars: { 'autoplay': 1, 'playsinline': 1 },
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
event.target.playVideo();
}
</script>
</body>
</html>
The official statement "Due to this restriction, functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments.
Reference: https://developers.google.com/youtube/iframe_api_reference
There is a way to make youtube autoplay, and complete playlists play through. Get Adblock browser for Android, and then go to the youtube website, and and configure it for the desktop version of the page, close Adblock browser out, and then reopen, and you will have the desktop version, where autoplay will work.
Using the desktop version will also mean that AdBlock will work. The mobile version invokes the standalone YouTube player, which is why you want the desktop version of the page, so that autoplay will work, and so ad blocking will work.
How to use a Youtube channel live url to embed and autoplay. Instead of Video ID that has to be constantly updated for live stream changes.
I mixed two sets of code and came up with a working auto play Youtube video embed from a channel live stream.
My thanks to both of the other contributors for their help. Hopefully this helps someone else some time.
Example stream
https://www.youtube.com/embed/live_stream?channel=UCwobzUc3z-0PrFpoRxNszXQ
The code below by Zubi answered Nov 25 '16 at 7:20 works with Youtube videos.
With code by Darien Chaffart found at
https://stackoverflow.com/a/61126012/1804252
Example
<html>
<head>
</head>
<body>
<center>
<script src="https://www.youtube.com/iframe_api"></script>
<!-- Insert Livestream Video -->
<iframe id="live-video" src="https://www.youtube.com/embed/live_stream?channel=UCwobzUc3z-0PrFpoRxNszXQ&enablejsapi=1" width="100%" height="100%" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen enablejsapi="1"></iframe>
<!-- Basic API code for Youtube videos -->
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('live-video', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady() {
var url = player.getVideoUrl(); /*Use Youtube API to pull Video URL*/
var match = url.match(/[?&]v=([^&]+)/);
var videoId = match[1]; /*Use regex to determine exact Video URL*/
// Insert a new iFrame for the livestream chat after a specific div named chatframe*/
var livevid = document.createElement("iframe");
livevid.src = 'https://www.youtube.com/live_chat?v=' + videoId + ''
livevid.width = '100%';
livevid.height= '100%';
document.getElementById("chatframe").appendChild(livevid);
}
function onPlayerStateChange() {
}
function onPlayerReady(event) {
event.target.playVideo();
}
// 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, 90000000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</center>
</body>
</html>
Related
I am using youtube embed to display a video. I need to autoplay when site is opened
<iframe class="slider-image-mockup align-center" width="100%" height="750" src="https://www.youtube-nocookie.com/embed/Y-p828Jy8C8?rel=0&controls=0&autoplay=1&loop=1&playlist=Y-p828Jy8C8&showinfo=0" frameborder="0" allow="autoplay; loop; encrypted-media" allowfullscreen></iframe>
I am using this code before it was working fine but for past few days. Autoplay is not working...
It may sound crazy but I didn't change anything in my code.
its showing like below after clicking of play button only video is playing
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<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>
</body>
</html>
now I have changed the url
from : https://www.youtube-nocookie.com/embed/Y-p828Jy8C8?rel=0&controls=0&autoplay=1&loop=1&playlist=Y-p828Jy8C8&showinfo=0
To : https://www.youtube.com/embed/Y-p828Jy8C8?rel=0&controls=0&showinfo=0&autoplay=1&loop=1&playlist=Y-p828Jy8C8
now its working... Thank you..
I've made a live-feed for my website. Every 30 seconds the content reloads. But now I have a problem. When I'm adding an embedded video (from Youtube) or an HTML5 <video>, I can't play the video completely because of the reload. Is it possible to stop the auto reload when the video is playing, and restart the reload when the video has stopped?
This is what I use for the reload:
$(document).ready(function() {
$("#updates").load("updates.php");
var refreshId = setInterval(function() {
$("#updates").load('updates.php' + '?randval=' + Math.random());
}, 30000);
$.ajaxSetup({
cache: false
});
});
You can video my live-feed here.
The following is untested. One thing beforehand - you can't handle an html5 video element the same way like an embedded youtube iframe.
In case you have a video element you can interact directly with it and use the eventhandlers for play, pause and end to handle your request. A possible solution could look something like this:
$(function() {
var refreshId;
// collection of all video elements on your page
var videos = $('video');
// disable reload by clearing the interval
function blockReload() {
clearInterval(refreshId);
}
// your existing reload function
function startReload() {
refreshId = setInterval(function() {
$("#updates").load('updates.php' + '?randval=' + Math.random());
}, 30000);
}
// loop over all video elements on your page and bind
// three event handlers, one for playing, one for pausing
// and one for an ended video.
videos.each(function() {
this.addEventListener('playing', blockReload);
this.addEventListener('paused', startReload);
this.addEventListener('ended', startReload);
});
});
Since you can't control embedded elements directly, you'll need to work with the youtube API.
Instead of using the iframe from youtube, you use the API to load the video like this (example from the API page):
// This code loads the IFrame Player API code asynchronously.
// you could also use a normal script tag in that case you would load
// the lib each time.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
Next you load the video via the script library:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360'
width: '640',
videoId: 'YOURVIDEOID',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Now you can interact with the youtube video:
function onPlayerStateChange(event) {
// check if video is running...
if (event.data == YT.PlayerState.PLAYING) {
// disable interval
blockReload();
} else {
// restart interval
startReload();
}
}
I found this solution by trial and error (I used axel.michel's functions Blockreload() and StartReload()).
You can add onplay="" and onended="" to the video-tag (it also works for the audio-tag). onplay="" loads the function Blockreload(), onended="" loads the function StartReload().
It looks like this:
<video id="test" onplay="BlockReload()" onended="StartReload()" width="800" controls>
<source src="*video source*">
Jouw browser ondersteund onze videoplayer niet.
</video>
I want to lazy load the youtube video with iframe API. ie. load only the poster image in the beginning and when user clicks on it then only load the actual image and its content.
Most of this is taken from the getting started section on the youtube page.
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<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>
This example loads the video when it is ready.
So we change it up a bit to add in a placeholder image and on click hide the image and play the video.
Wrap the tag (step 2) in function
function loadYT() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
Add an image Check this question for more details on sizes.
<div id="placeholder">
<img src="http://img.youtube.com/vi/M7lc1UVf-VE/sddefault.jpg" />
</div>
Then on click hide the placeholder image and load the player
document.getElementById("placeholder").addEventListener("click", function(){
this.style.display = 'none';
loadYT()
});
Final result can be seen below.
<div id="placeholder">
<img src="http://img.youtube.com/vi/M7lc1UVf-VE/sddefault.jpg" />
</div>
</div>
<div id="player"></div>
<script>
document.getElementById("placeholder").addEventListener("click", function(){
this.style.display = 'none';
loadYT()
});
// 2. This code loads the IFrame Player API code asynchronously.
function loadYT() {
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>
Why load the videos on click, and not just when the user sees them? Use jQuery.Lazy and you have nothing more to do. :)
Add the Plugin to your Page: (you will need jQuery or Zepto as well)
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/jquery.lazy.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/plugins/jquery.lazy.youtube.min.js"></script>
Prepare your iFrames: (note the data-loader and data-src attributes)
<iframe data-loader="youtube" data-src="1AYGnw6MwFM" width="560" height="315"></iframe>
And start using Lazy:
$(function() {
$("iframe[data-src]").Lazy();
});
That's it! The iFrames will be loaded whenever the user reaches them by scrolling. More inormations here.
<iframe loading="lazy"
This HTML feature allows lazy loading YouTube iframe embeds only when the user scrolls over them, without any extra JavaScript (the YouTube video is of course automatically loaded via JavaScript in the iframe however).
Here is a working jsfiddle: https://jsfiddle.net/cirosantilli/3p0tk5nc/1/ that I have tested on Chromium 81. You can see on the developer tools "network" tab that the frames only load when you scroll over them.
It does not work on Stack Overflow snippets for some reason however because YouTube videos appear to not work on Stack Overflow in general, not because of loading="lazy" in particular.
More details at: lazy load iframe (delay src http call) with jquery
How about this?
HTML
<div class="wrapper">
<ul>
<li><a title="video 1" data-video="http://www.youtube.com/embed/X0DeIqJm4vM">Motherlover</a></li>
<li><a title="video 2" data-video="http://www.youtube.com/embed/GI6CfKcMhjY">Jack Sparrow</a></li>
<li><a title="video 3" data-video="http://www.youtube.com/embed/TcK0MYgnHjo">Ras trent</a></li>
<li><a title="video 4" data-video="http://www.youtube.com/embed/8yvEYKRF5IA">Boombox</a></li>
<li><a title="video 5" data-video="http://www.youtube.com/embed/6_W_xLWtNa0">Shy Ronnie 2</a></li>
</ul>
<iframe id="videoArea" width="350" height="250" src="http://www.youtube.com/embed/X0DeIqJm4vM" frameborder="0" allowfullscreen></iframe>
</div>
JS
var initVideos = function() {
var videoArea = $("#videoArea"),
divs = $("ul li a"); // or some other data format
// bind your hover event to the divs
divs.click(function(ev) {
ev.preventDefault();
videoArea.prop("src", $(this).data('video'));
divs.removeClass("active");
$(this).addClass("active");
});
};
// once the DOM is ready
$(function() {
initVideos();
});
DEMO
I just lazy load the thumbnail and only load the real video if the visitor is hovering the thumbnail. For Privacy reasons you can also make him click a confirmation before loading the video from youtube.
<?php $youtubevideo="Video ID1"; $youtubezaehler=$youtubezaehler+1;?>
<br>
<div align="center" class="video-container" onmouseover="video<?php echo($youtubezaehler);?>()">
<div style="position:relative;">
<img loading="lazy" id="vorschaubild<?php echo($youtubezaehler);?>" class="" src="https://img.youtube.com/vi/<?php echo($youtubevideo);?>/<?php echo $youtube_aufloesung; ?>" width="100%" alt="Lade...">
<div id="play<?php echo($youtubezaehler);?>" style="position:absolute; top:30%; left:46%; width:10%;"><img src="play.gif" alt="Play" style="width:100%;"></div>
</div>
<script type="text/javascript">
<!--
//JavaScript zum DSGVO konformem und Ladezeitoptimierten Einbinden der Youtube Videos erst bei Nutzung
function video<?php echo($youtubezaehler);?>() {
if(document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").style.visibility=="hidden") return false; //Damit das Video nicht beim abspielen versehntlich neu geladen wird
document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").height = "1px";
document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").style.visibility="hidden";
document.getElementById("play<?php echo($youtubezaehler);?>").style.visibility="hidden";
document.getElementById("video<?php echo($youtubezaehler);?>").src = "https://www.youtube-nocookie.com/embed/<?php echo($youtubevideo);?>?rel=0";
}
// -->
</script>
<iframe title="Video" id="video<?php echo($youtubezaehler);?>" src="" frameborder="0" allowfullscreen></iframe>
</div>
Finally it worked, below code is in angularJS.
HTML
<div data-ng-repeat="video in videoIds track by $index">
<div id="uniQueId" ng-click="playVideo(video, 'player' + $index)">
<div class="video-play-button"></div>
</div>
</div>
JS
$scope.playVideo = function(videoId, id) {
$scope.players[id] = new YT.Player(id, {
videoId: videoId,
width: '400',
height: '300',
playerVars: { 'autoplay': 1 },
events: {
'onStateChange': $scope.onPlayerStateChange
}
});
};
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>
How do I set the youtube embedded player to unmute upon clicking it. You can see the embedded player i'm referring to at http://www.harvestarmy.org home page. It's the one at the right where it says "Latest Videos from YouTube. I set it up to be muted by default, but I want it to automatically unmute when someone clicks it.
Here is the code I used:
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
// This is a protocol-relative URL as described here:
// http://paulirish.com/2010/the-protocol-relative-url/
// If you're testing a local page accessed via a file:/// URL, please set tag.src to
// "https://www.youtube.com/iframe_api" instead.
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: '98',
width: '175',
playerVars: {
'list': 'UUFwY5Al1Doy7f0MdKnJ-gaw',
'modestbranding': 1,
'showinfo': 0,
'autoplay': 1
},
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
}
</script>
Thank you for that answer! I implemented it a little differently, adding it to the onYouTubeIframeAPIReady function.
I also reversed the initialized value of the isUnMuted variable. Functionally it is the same, but makes more sense this way.
var player;
var isUnMuted = false;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('youTube', {
videoId: '[myVideoId]',
playerVars: {
'rel': 0,
},
events: {
'onReady': function() {
player.mute();
player.playVideo();
},
'onStateChange': function () {
if (player.isMuted() && player.getPlayerState() == 2 && !isUnMuted) {
player.unMute();
player.playVideo();
isUnMuted = true;
}
}
}
});
}
This mimics closely the behavior of embedded videos in a Facebook newsfeed.
I don't think it is possible, because there is not such thing as a 'click' or 'activate' event. However, you may try adding an event handler to the "onStateChange" event and unmute and unpause your player. I haven't tried it, but give it a try and see if this works:
var isUnMuted = true;
player.addEventListener("onStateChange", function(event) {
if( player.isMuted() && player.getPlayerState() == 2 && isUnMuted ) {
player.unMute();
player.playVideo(); // resume playback
isUnMuted = false; // you want to run this once only!
}
});
This works. But unfortunately the pause icon fades in when the video is clicked. Even the video continues to run it is not a clean solution.
I fixed it by placing a <div> with exactly the same size above the actual video iframe and use its click() function to unmute the video.
HTML:
<div class="video-container">
<div class="video-dummy">
</div>
<div id="player">
</div>
</div>
CSS:
.video-container {
position: relative;
width: 640px;
height: 390px;
}
.video-dummy {
width: 640px;
height: 390px;
position: absolute;
}
Javascript:
$('.video-dummy').click(function(){
player.unMute();
});
This works out well for me.