I want to have a mute button for my site, so when it's pressed it will unmute / mute the audio playing from the background video.
The js I have rn is this. Is there any way I can implement a button with this code?
`enter code here
var videos = [
'D1sZ_vwqwcE',
'BC_Ya4cY8RQ',
'HPc8QMycGno',
'JDglMK9sgIQ',
'hgKDu5pp_fU',
'oKMNj8v2gKE',
'TfnRTifSWh0',
'xO3aB5C3dpQ',
'v5hepekcHkk',
'4kjpZ_sPxzc',
];
var index=Math.floor(Math.random() * videos.length);
var html='<div class="video-background"><div class="video-foreground"><iframe frameborder="0" src="https://www.youtube.com/embed/' +videos[index] + '?controls=1&showinfo=0&rel=0&autoplay=1&iv_load_policy=3&&mute=1" allow="autoplay""></iframe></div></div>';
document.write(html);
site for reference: https://enph.la
I deserve no credit for this answer, but wanted to point out that the described issue actually got solved in Custom mute/unmute button Youtube API quite well using the YouTube API as it can be seen in this working example from Marco Aurelio Fernandez Reyes
(somehow it just works on jsfiddle, but not on stackoverflow...):
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('youtube-video', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady() {
console.log("hey Im ready");
//do whatever you want here. Like, player.playVideo();
}
function onPlayerStateChange() {
console.log("my state changed");
}
document.getElementById("mute").addEventListener('click', function(event) {
console.log(player);
if (player.isMuted()) {
player.unMute();
} else {
player.mute();
}
});
#mute {
width: 50px;
height: 50px;
background-color: red;
}
<iframe id="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&
autoplay=1
&disablekb=1
&enablejsapi=1
&loop=1
&controls=0
&mute=0" frameborder="0" enablejsapi="1" allowfullscreen></iframe>
<div id="mute">
</div>
<p>
Press red square to mute/unmute
</p>
Since a comment easily be overlooked, I just wanted to point out the working solution.
Related
I'm trying to make a iframe Youtube plays after my preloaded screen fade out. Currently, I'm using jQuery to fade out the preloader screen.
Which I'm using this code there
$(window).on("load", function () {
$('.pre-loader').fadeOut(1000);
});
Somehow his set of code can't run if I insert this in the windows.on load function. I have to place it outside the window.on load function. Couldn't understand why.
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('existing-iframe-example', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
console.log('player ready');
event.target.playVideo();
}
function onPlayerStateChange(event) {
console.log('event change')
}
This is how the iframe code I'm using in my html
<iframe id="existing-iframe-example" class="yt-video"
src="https://www.youtube.com/embed/niRUIXag55I?enablejsapi=1&rel=0" frameborder="0"
allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
In my console.log, I can see 'player ready' and 'event change'. But the youtube video just can't play.
Any help here will be deeply appreciated.
Is it possible to detect if a video has been removed or is no longer available on Youtube using the iFrame API?
The following code will detect changes to the youtube iframe but the only data point I can find thats remotely close is -3 which means unstarted but this could be applicable to any working video as well.
CodePen
<iframe id="yt-iframe" width="630" height="354" src="http://www.youtube.com/embed/Rlm8YH2i9gY?enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>
<script type="text/javascript">
var tag = document.createElement('script');
tag.id = 'yt-script';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
console.log('yt scripts loaded');
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('yt-iframe', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
console.log('video player ready');
}
function onPlayerStateChange(event) {
console.log(event.data);
}
</script>
You can detect before playing the video by checking the duration of the video, if duration of the video is 0 seconds then it is highly likely to be deleted/can't be played
<iframe id="yt-iframe" width="630" height="354" src="http://www.youtube.com/embed/tPEE9ZwTmy0?enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>
<script type="text/javascript">
var tag = document.createElement('script');
tag.id = 'yt-script';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
console.log('YT scripts loaded');
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('yt-iframe', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
console.log('Video player ready');
if (event.target.getDuration() <= 0) {
console.log('Video likely to be removed');
}
}
function onPlayerStateChange(event) {
console.log(event.data);
}
</script>
Setup an onError event handler and check for event.data === 100. The YouTube IFrame Player API describes all of the player error events.
No, atleast not straightforward.
Any idea why this script doesn't work? All I want is to track onStateChanged event, but that is never called either.
When I open the html document with below code, I have no errors, the youtube script loads just fine, the player object is not undefined, looks fine too.
$(document).ready(function(){
loadScript();
});
function loadScript() {
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
}
});
alert(player);
}
var done = false;
function onPlayerStateChange(event) {
alert('state changed');
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 3000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
function onPlayerReady(event) {
event.target.playVideo();
}
My iframe:
<iframe id="player width="400" height="300" src="https://www.youtube.com/embed/j0pJekWgeFE" frameborder="0" allowfullscreen></iframe>
See fiddle: https://jsfiddle.net/rg2uy1f8/
I found an answer here: How do I get the reference to an existing YouTube player?
The reason my solution didn't work, was that my iframe was missing an attribute: enablejsapi="1" and also I was missing: ?enablejsapi=1 in YouTube video url.
You may find the working solution here: http://jsfiddle.net/bf7zQ/2/
I am trying to change the video playing in the YouTube iframe in the cleanest way possible and a few months ago I had this code working, but YouTube changed their API and it stopped working for me. Now the onPlayerStateChange event is not firing after I switch out the video's SRC attribute to switch the video that is playing. I'm an amateur to coding so I may be missing something simple here, but any input would be greatly appreciated.
Below is a code that loads a YouTube video and when it ends, there's an alert that automatically pops up for you. However, when you click the button and switch the video by switching out the SRC attribute, the alert function stops working and its as if the entire onPlayerStateChange function stops working. I could not get it working in jsfiddle, but a link to a live demo can be found at http://thetunedrop.com/test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="player"></div>
<button class="button" data-youtubeid="b-3BI9AspYc">BUTTON</button>
</body>
</html>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="jquery/js/jquery-ui-1.8.22.custom.min.js"></script>
<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');
}
}
function load_ytid(youtubeid){
$("#player").attr("src", "http://www.youtube.com/embed/" + youtubeid + "?fs=1&autoplay=1");
}
$(document).ready(function(){
$(".button").on("click", function(){
var youtubeid = $(this).data("youtubeid");
load_ytid(youtubeid);
});
});
</script>
Try this instead :
<!DOCTYPE html>
<html>
<body>
<script src="jquery-1.10.2.min.js"></script>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<button class="button" data-youtubeid="b-3BI9AspYc">BUTTON</button>
<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: '0Bmhjf0rKe8',
playerVars: { 'autoplay': 1, 'controls': 1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var playerReady = false;
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
playerReady = true;
}
// 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.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED ) {
alert('done');
}
}
$(".button").on("click", function(){
player.loadVideoById("Vw4KVoEVcr0", 0, "default");
});
</script>
</body>
</html>
The fiddle here : http://jsfiddle.net/QtBlueWaffle/8bpQ8/1/
Hope this helps
I had kind of the same problem (I Think)... I wanted the user to be able to change the content for multiple players, and this is what works for me: I call the youtube api with a onload function additional to the new Youtubelink, so that reloads every time the iframe changes.
MY HTML:
<iframe onload="floaded1()" id="player1" width="240" height="220"
src="http://www.youtube.com/embed/0Bmhjf0rKe8
?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1"
frameborder="0" allowfullscreen> </iframe>
MY JS:
function floaded1() {
player1 = new YT.Player('player1', {
events: {
'onStateChange': function (event) {
if (event.data == 0) {
alert('done');
};
}
}
});
}
WHAT I LOAD WITH A VIDEO PICKER:
html += '<iframe onload="floaded1()" id="player1" width="240" height="220"
src="http://www.youtube.com/embed/'+YouTubeVideoId+'?enablejsapi=1&rel=0&
showinfo=2&iv_load_policy=3&modestbranding=1" frameborder="0" allowfullscreen>
</iframe>';
I have used a iframe video in my web page. This is my html code
<iframe id="video1" width="520" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
Play video
I need to play video onclick the play video link. How can i do that?
This works, it appends autoplay=1 to the url causing the video to start playing.
addendum: If your video's source does not already have a querystring then it would be prudent to add a ? instead of a &, as is sometimes the case. This can be done by looking for its existence.
<iframe id="video1" width="520" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
Play video
<script>
//use .one to ensure this only happens once
$("#playvideo").one(function(){
//as noted in addendum, check for querystring exitence
var symbol = $("#video1")[0].src.indexOf("?") > -1 ? "&" : "?";
//modify source to autoplay and start video
$("#video1")[0].src += symbol + "autoplay=1";
});
</script>
However, most people inherently understand that if they want a video to play, they will just click on it and I would suggest just leaving that to them or starting the video off with autoplay.
Also need to mention that autoplay does not work on mobile devices (powered by Android or iOS)
I correctly set in end src - ?autoplay=1
<iframe id="video1" width="450" height="280" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
Play button
<script>
$("#playvideo").click(function(){
$("#video1")[0].src += "?autoplay=1";
});
</script>
Here is another example. Check this here: https://codepen.io/rearmustak/pen/VXXOBr
const Player = document.getElementById('player2');
const PlayBtn = document.getElementById('play');
const stopBtn = document.getElementById('stop');
let times = 0, playY;
const playVideo = PlayBtn.addEventListener( 'click' , () => {
if(times == 0){
playY = Player.src += '?autoplay=1';
times = 1;
}
});
stopBtn.addEventListener( 'click' , () => {
playY = playY.slice(0, -11);
Player.src = playY
times = 0;
});
.video-frame{
overflow: hidden;
margin-bottom: 10px;
}
button{
border: none;
background-color: #e75252;
color: #ffffff;
padding: 10px 15px;
border-radius: 3px;
cursor: pointer;
}
button:focus{
outline: 0;
}
#stop{
background-color: #ff0002;
}
<h1>Youtube video Play/Stop</h1>
<div class="video-frame">
<iframe id="player2" width="560" height="315" src="https://www.youtube.com/embed/cs1e0fRyI18" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
<button id="play">Play</button>
<button id="stop">Stop</button>
since the first answer is already 3 years old, let me point to the Youtube Player API. With that you can remote control your embedded player.
See https://developers.google.com/youtube/iframe_api_reference?hl=en
With a small adjustment, you can start the video via link and without reloading the entire iframe:
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<!-- The Play-Link will appear in that div after the video was loaded -->
<div id="play"></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();
document.getElementById('play').innerHTML = 'Play Video';
}
function play(){
player.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>
here is link to example http://jsfiddle.net/WYwv2/5/
Check out this
<!DOCTYPE html>
<html>
<body>
Play video
<iframe id="video1" width="520" height="360" frameborder="0" ></iframe>
<script>
function playme() {
document.getElementById("video1").src = 'http://www.w3schools.com/tags/mov_bbb.mp4';
}
</script>
</body>
</html>
We set the source of video dynamically.
it's work for me.
please Check out this.
$("#player").on("pause", function(e) {
clearTimeout(playTimeout);
});
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', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 2000);//replace time here
$("#player").get(0).load();
$("#player").get(0).pause();
done = true;
}
}
function stopVideo() {
player.stopVideo();
}