I am looking to catch the sound provided in an iframe youtube video in order to stop/play it through a sound button.
Since the volume opt does not work anymore I tried this.
function toggleSound() {
var soundElem = document.getElementbyId("frame1") // also tried with iframe.getElementbyId()
soundElem.volume = 0.3
if (soundElem.paused) {
soundElem.play()
}
else
soundElem.pause()
}
//my yt video
<iframe id=iframe1 src="//www.youtube.com/embed/YOUTUBECODE?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
// my volume btn
<div class=volume-button onmousedown=toggleSound();>
I can't get the youtube audio and the youtubeAPI does not provide me an event with an external button ?
Kind Regards,
With the IFrame Player API you can use the mute method to mute the sound with an external event:
var player
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: 1280,
height: 720,
videoId: 'M7lc1UVf-VE'
})
}
function toggleSound() {
if (player.isMuted()) {
player.unMute()
} else {
player.mute()
}
}
Related
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>
I have Youtube embed code using iframe
<iframe title="YouTube" src="http://www.youtube.com/embed/aaabbbcccddd?wmode=transparent&autoplay=0" allowfullscreen="allowfullscreen"></iframe>
I want that if users click the "Play" button, it automatically goes fullscreen.
As opposed to the user should click "Play" and click "Fullscreen" button -- I want to skip that click "Fullscreen" part.
Is this possible?
Do I need to use Youtube's Javascript API?
Does it have something like this:
youtube.onPlayButtonClicked(function() {
youtube.fullscreen();
});
Thank you in advance!
It's possible with the youtube API.
var player, iframe;
var $ = document.querySelector.bind(document);
// init player
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '200',
width: '300',
videoId: 'dQw4w9WgXcQ',
events: {
'onReady': onPlayerReady
}
});
}
// when ready, wait for clicks
function onPlayerReady(event) {
var player = event.target;
iframe = $('#player');
setupListener();
}
function setupListener (){
$('button').addEventListener('click', playFullscreen);
}
function playFullscreen (){
player.playVideo();//won't work on mobile
var requestFullScreen = iframe.requestFullScreen || iframe.mozRequestFullScreen || iframe.webkitRequestFullScreen;
if (requestFullScreen) {
requestFullScreen.bind(iframe)();
}
}
You can have an exemple at this link :
https://codepen.io/bfred-it/pen/GgOvLM
Youtube allows embedding user created playlist with the help of iframe code. I would like to embed them in a webpage to be played back on Android (Kitkat 4.4) tv box hardware. However it requires user to first click on the video.
As I found out that Apple iOS and Android disables autoplay on most mobile platforms to avoid poor user experiences
However, is it possible to simulate a user click on the iframe using Jquery or pure JS solution (preferred). Something like this:
function myFunction() {
setTimeout(function() { ("#myiframe").triggerHandler('click'); },3000)
};
I'd be very grateful if somebody can help me with this as this functionality is crucial for my purpose and I have searched extensively but couldn't get a proper solution.
thanks
dkj
Good morning dkjain,
as far as I've read in the Youtube Player API docs, there are several events triggered as soon as the Player is loaded, one of these events that should be used is the onReady() event.
Here's some updated code on how to auto-play a single video or a playlist:
HTML:
<div id="player"/>
will be the placeholder for the Youtube player
Playing a playlist (with playerVars):
JS:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
playerVars: {
'listType': 'playlist',
'list': 'PLi5VEqNXXQjVJ4-xZb92wTUawkSQRal0u'
},
events: {
'onReady': onPlayerReady
}
});
}
window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
// as soon as the player is loaded, start the playback
function onPlayerReady(event) {
event.target.playVideo();
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
document.head.appendChild(tag);
There is also an autoPlay: 1 playerVar, but this does not seem to be available on mobile plaforms: https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations
Play a single video
JS:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'nhX4rQ79C1A',
events: {
'onReady': onPlayerReady
}
});
}
window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
// as soon as the player is loaded, start the playback
function onPlayerReady(event) {
event.target.playVideo();
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
document.head.appendChild(tag);
JSFiddles showing the above code:
Single video: http://jsfiddle.net/Moonbird_IT/akjpmvpf/
Playlist: http://jsfiddle.net/Moonbird_IT/akjpmvpf/4/ (updated again)
Let me know if we are going in the right direction :-)
So I'm writing a TamperMonkey script that sends specific videos to YouTube's embedded player however I want to automatically send them back once the video is finished.
So for example, video http://youtube.com/watch?v=XXXXX it would redirect to http://youtube.com/v/XXXXX. And then, once the video is complete, it would use window.history.go(-2) (as -1 would go to the normal page causing a loop).
The problem I'm having is that I haven't been able to get the second part, the function that runs when the video finishes, to work.
I have tried following the api and looking at other peoples problems and seeing what helped them but I can't seem to get it.
At the moment this is the code I have.
$(document).ready( function() {
var loc = document.location.href;
var l = loc.split('/');
var s = l[4];
var id = s.split('?')[0]
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '100%',
width: '100%',
videoId: id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
alert('spotted');
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
window.history.go(-2);
}
}
});
I would appreciate it if someone would work with me to get this script working.
Thanks.
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.