What I'm trying to do: Create a list of items which contains a link to play audio from a youtube video beside each item
What I'm currently doing: I'm able to do this for a single item using the below:
<div data-video="VIDEO_ID"
data-autoplay="0"
data-loop="1"
id="youtube-audio">
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>
This creates a play button and works perfectly on a single item, however will not work with multiple items on the same page presumably since they all use the same ID. Creating a different ID causes the player to not function. Creating two different data-video's with the same ID will only allow the first one to play, the other will appear correctly but not operate when pressing play.
Looking for solution: Preferably how to use the existing script for multiple videos on the same page. Otherwise an alternative solution for playing audio only on youtube videos with a custom play button would be great.
Thanks!
If you want you can just copy paste your code like this
https://jsfiddle.net/8wkjqf3m/
and it works, I'm not sure if you were having a problem doing that or if your problem was elsewhere. It is of course very sloppy looking and the code should be reworked so that you don't have to hard code every function for every video.
I tried to do everything dynamically and failed. I'm not sure if it is possible to dynamically make a function that makes a "new YT.player" for every video id you have and also have the onPlayerReady and onPlayerStateChange functions dynamically made to go with it. I'm sure there is some way but I couldn't figure it out.
The idea though is to make multiple "youtube-audio" divs with different ids for however many youtube players you want to have and have matching multiple "youtube-player" divs for the iframe to function. You can generate that part with javascript if you want so that you don't have to pollute your code with a bunch of repetitive html.
You can make all of your ids dynamically too.
var array = ['put a video id here','put a video id here','put a video id here'];
array = array.map(function(element,index) {
var div = document.createElement('div');
div.setAttribute('id', 'youtube-audio-' + index);
return {'videoId': element, 'div': div };
}
You can just have an array holding the youtube video ids and then initialize all of the divs data-video attributes using
document.getElementById("youtube-audio-1").dataset.video = //youtube video id
I don't see the point in doing all of that dynamically though if there is no way to get around copy pasting x number of "new YT.player"s and "onPlayerReady"s etc...
Good Luck, let me know if I was in the right area or if that was not what you wanted
I have modified the second script so it works as you (or I) want.
To use it use classes instead of IDs. Like the following:
<div data-video="NQKC24th90U" data-autoplay="0" data-loop="1" class="youtube-audio"></div>
<div data-video="KK2smasHg6w" data-autoplay="0" data-loop="1" class="youtube-audio"></div>
Here is the script:
/*
YouTube Audio Embed
--------------------
Author: Amit Agarwal
Web: http://www.labnol.org/?p=26740
edited by Anton Chinaev
*/
function onYouTubeIframeAPIReady()
{
var o= function(e, t)
// This function switches the imgs, you may want to change it
{
var a=e?"IDzX9gL.png":"quyUPXN.png";
//IDzX9gL is the stopped img and quyUPXN the playing img
t.setAttribute("src","https://i.imgur.com/"+a)
// folder or web direction the img is in. it can be "./"+a
};
var counter = 0;
var bigE = document.querySelectorAll(".youtube-audio");
bigE.forEach(function(e)
{
var t=document.createElement("img");
t.setAttribute("id","youtube-icon-"+counter),
t.style.cssText="cursor:pointer;cursor:hand",
e.appendChild(t);
var a=document.createElement("div");
a.setAttribute("id","youtube-player-"+counter),
e.appendChild(a);
t.setAttribute("src","https://i.imgur.com/quyUPXN.png");
e.onclick=function()
{
r.getPlayerState()===YT.PlayerState.PLAYING||r.getPlayerState()===YT.PlayerState.BUFFERING?(r.pauseVideo(),
o(!1, t)):(r.playVideo(),
o(!0, t))
};
var r= new YT.Player("youtube-player-"+counter,
{
height:"0",
width:"0",
videoId:e.dataset.video,
playerVars:
{
autoplay:e.dataset.autoplay,loop:e.dataset.loop
},
events:
{
onReady:function(e)
{
r.setPlaybackQuality("small"),
o(r.getPlayerState()!==YT.PlayerState.CUED, t)
},
onStateChange:function(e)
{
e.data===YT.PlayerState.ENDED&&o(!1, t)
}
}
})
counter++;
});
}
Related
I am creating a chrome extension that adds a button to the youtube player HUD (to the left of the watch later button). This works fine, but the only problem is that when the HUD autofades after a few seconds of inactivity, this button element doesn't.
I've added the button to the following div using javascript:
<div class="ytp-chrome-top-buttons"> </div>
and my button looks like this:
<button class="customClass" id="customID" title="custom title"><svg class="customClass"></svg></button>
I've looked through the source of the page to try and see how exactly youtube makes the other icons disappear, and whether I can copy a class to my svg to make it disappear, but I haven't been able to find it.
I've looked at using a timer and javascript to make the element disappear, but I figured if the functionality is already there, why complicate it.
As a last resort I will be resorting to using the timer method, but I'd much prefer using CSS classes.
I have had a cursory glance into the Youtube Player API, but to be frank, I'm having a hard time understanding how it works (While I have a few years of programming experience, I only started learning javascript, HTML, and CSS yesterday). I also understand that this API is only for embedded youtube videos?
To clarify, I DO know how to use API's in javascript, just not this particular one. I have used the youtube data API to implement the button's functionality successfully.
Any help is appreciated.
Thanks.
If you examine the element changes, you can see that the class list of the video has changed with the change of the bottom bar. When the bottom bar is hidden, the ytp-autohide class is added. Keeping this in mind, after scanning the class changes with the mutation observer, you will reach the desired result when the ytp-autohide class's existence status changes.
var video = document.querySelector("#movie_player");
var lastState = video.classList.contains('ytp-autohide');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.attributeName == "class"){
var currentState = mutation.target.classList.contains('ytp-autohide');
if(lastState !== currentState) {
lastState = currentState;
if(currentState)
console.log("Hided");
else
console.log("Shown");
}
}
});
});
observer.observe(video, {attributes: true});
I have some embed code like:
<iframe id="video1" class="video" src=""//www.dailymotion.com/embed/video/VIDEO_ID?autoPlay=1&wmode=transparent&loop=1&controls=0&showinfo=0&api=1&endscreen-enable=0&mute=1" allowfullscreen="true" frameborder="0" width="560" height="349"></iframe>
I am trying to access this video using Javascript but the Video ID is not known in advance (it must be able to be set within our CMS and be changed by any editor). Also it is possible to have more than one video on the page. Hard-coding the video ID(s) in my .js file is not possible.
Using the Javascript API, I need to write a custom play/pause function (passing in the button object they clicked) and also to detect when the video has ended and re-start it (to imitate looping, which Dailymotion apparently does not support for some reason). But it seems a call to:
DM.Player(document.getElementById(iframeID), { video: VIDEO_ID})
requires the video's ID to be known (I do know the iFrame ID where the video is but apparently that isn't enough to access the player like it is for other video platforms).
I then need to be able to create a function to call play or pause based on whether the user has clicked the play/pause toggle on a specific video. My Javascript knowledge isn't great, but I have been able to do this with other platforms by knowing the iframe ID. The play/pause does work if I hard-code a video ID but only if there is one video on the page and only if I do not try to "loop" the video.
This is a private video, if that matters - we want it to only be viewed on our website and not on Dailymotion.
Pseudo-code greatly appreciated as I find their API documentation a bit incomplete for a newcomer (such as not specifying if parameters are required or optional, and not listing available options like for params and events during DM.Player initialization)
EDIT: Here is how I access the video API with other video hosting services (YouTube, Vimeo, Brightcove, etc)
I build an array of all HTML elements with a certain class name (recall there can be more than one video). Say the class name is ".video" so I build an array of all ".video" on the page and their corresponding HTML id. I then use document.getElementById to populate the array with the players.
Then in the play/pause click function, I can access the video like so:
var player = players[index];
var state = player.getPlayerState();
if (state == 1) {
player.pauseVideo();
}
else {
player.playVideo();
}
This does not work for Dailymotion because the actual DM Video ID (and not the HTML element's ID) must be known in advance. I was wondering if there is a way to access the video via the Javascript API without knowing the video ID?
I don't use DailyMotion API but I knocked up this experiment which might be useful to you.
See if the comments in my example code below help you to understand how to use your own buttons with JS functions and how to handle video "end" event etc.
<!DOCTYPE html>
<html>
<body>
<!-- 1. Load DailyMotion API (Javascript) -->
<script src='https://api.dmcdn.net/all.js'> </script>
<!-- 2. Create container for DM Player instance -->
<div id='player'></div>
<!-- 3. Javascript stuff goes here -->
<script>
//Set VIDEO_ID (retrieve or update from your CMS)
//**example** var VIDEO_ID = get_video_id.php **where PHP returns/echo the text of ID**
var VIDEO_ID = "xwr14q"; //update this via your CMS technique
//Create DM Player instance//
var player = DM.player(document.getElementById('player'), {
video: VIDEO_ID,
width: "100%", height: "100%",
params: { autoplay: false, mute: true }
});
//Handle video ending (seek back to zero time)//
player.addEventListener('end', function (evt) { evt.target.currentTime = 0; evt.target.play() } );
//Control functions for DM Player instance//
function func_Play()
{ player.play(); }
function func_Pause()
{ player.pause(); }
</script>
<p>
<!-- Buttons for play pause -->
<button onclick="func_Play()"> PLAY </button>
<button onclick="func_Pause()"> PAUSE </button>
</p>
</body>
</html>
Also regarding
"...It is possible to have more than one video on the page"
Do some "experience quality" tests. Just be sure your users don't mind multiple looping videos running at once (eg: may slow your page / their browser, or drain their data allowance if on mobile, etc).
To handle multiple videos, I would just put each video player in it's own HTML page (like above shown code) and then in main page just load multiple iframes pointing to each player's HTML.
I am embedding about 10 YouTube iframes in my page, all with their own custom play/pause buttons. I have used this solution to begin http://jsfiddle.net/buuuue/dzroqgj0/ but I'm not sure how to tweak this piece of the code to stop ANY other video that is playing if another one begins...
function stopVideo(player_id) {
if (player_id == "player1") {
player2.stopVideo();
} else if (player_id == "player2") {
player1.stopVideo();
}
}
For example, if player 1 is currently playing, and player 3 is played, I'd want player 1 to stop playing. I've also looked into this solution https://stackoverflow.com/a/38405859/1798756, but I think I need to create the players via JS so that I can also create the custom play/pause buttons.
Thanks in advance for any help!
After creating players push them onto an array.
var vids =[];
player1 = new YT.Player('player1', {
//stuff
});
vids.push(player1);
player2 = new YT.Player('player2', {
// stuff
});
vids.push(player2);
....
..
playerN = new YT.Player('playerN', {
// stuff
});
vids.push(playerN);
Every player object's id can be accessed by its a.id property(a is itself an object , id is a property(string) )
Now when user plays a given player you have to just pause all other except the one being played(id of which you get in stopVideo).Since you have id it's easy
function stopVideo(player_id) {
for(var i=0;i<vids.length;i++){
if (player_id !=vids[i].a.id)
vids[i].stopVideo();
}
}
Example : - http://jsfiddle.net/4t9ah1La/
If you are not creating player through scripts but rather just embedding iframes then this answer mentioned by vbence is enough , below is a demo of that with improvements suggested by Jennie
Example : - http://jsfiddle.net/fyb7fyw1/
All credits to respective original authors
So, I'm still new to javascript and everything. What I'm trying to do is when a small video is clicked, display it on the main big video above. This is the script so far, but I'm not sure what I need to add.
<script type="text/javascript">
$(document).ready(function() {
$(".littlevideo").click(function() {
var video = $(this).closest("div").find("video").attr("src")
$('#displayvideo').attr("src",video);
});
});
</script>
you want to do something like:
<script type="text/javascript">
$(document).ready(function() {
$(".littlevideo").click(function() {
var video = $(this).closest("div").find("video").attr("src")
$('#displayvideo').append("<iframesrc="+video+"></iframe>");
});
});
The append basically adds that HTML to the container. you do the +video+ because it adds whatever that value is, to the existing string. This is how you make it dynamic.
We need the rest of the page (preferably), but that piece of code should do what you are wanting. Basically, the code just takes the attributes of the element being clicked on (as long as it has a class of "littlevideo") and transfers it to the #displayvideo element (I'm guessing the "big video" you're talking about). Make sure the little video's elements/tags all have class="littlevideo", and the big video player element/tag has an attribute of id="displayvideo".
I'm currently working on a project which includes when the user hovers over a certain div then it will play the associated audio file and stop all other audio elements on the page that contain the class 'stoppable' in them.
I've got the code working but now I'm having that page as an iFrame on another page which can insert elements into the iframe, so I have to keep adding iframe.contents on elements to make them work.
On the code below it detects when the user has entered the div and plays the correct audio however it does not stop all the other audio elements.
I believe I have the incorrect syntax on the
$('.stoppable:not($("#new-audio-476333", iframe.contents()))
section, and I'm not sure what the correct syntax would be.
var iframe = $('#clientframe');
$('#476333',iframe.contents()).mouseenter(function() {
$('.stoppable:not($("#new-audio-476333", iframe.contents()))').each(function(){
this.pause(); this.currentTime = 0;
});
var audio = $('#new-audio-476333', iframe.contents())[0];audio.pause();audio.play(); });
Any help would be greatly appreciated.
Thanks!
-Hopeless
$('.stoppable:not(#new-audio-476333)', iframe.contents())
This means that elements with class name stoppable which its id is not new-audio-476333.