Play Youtube video in Basic HTML player with user control - javascript

I have a bunch of youtube urls which i would like to play. I want like to play only the audio content in a basic HTML player with user controls like Play, pause, next. I am unable to add user control functionality(Nor able to play the videos in a HTML player, i am embedding the youtube video), thus the user has to click on the play button of the next video every time a video is completed. Any help will be appreciated.

..continuing from the comments:
That's right you need to use js. I'll help you start: you can create an array with all your youtube urls:
var youtube_urls = ['https://www.youtube.com/watch?v=vpoi_l4jkyU', 'https://www.youtube.com/watch?v=Lml2SkB68ag', 'https://www.youtube.com/watch?v=awMiY-Ve1As'];
And then, using the api you listen for when a video is done playing and then start the next one:
Detect end video: How to detect when a youtube video finishes playing?
OR
Just create a playlist on youtube and embed the playlist. It'll loop through all the videos.

this should get you started:
// change this list to whatever you want
var urls = ['http://upload.wikimedia.org/wikipedia/en/f/f9/Beatles_eleanor_rigby.ogg',
'http://upload.wikimedia.org/wikipedia/commons/5/5b/Ludwig_van_Beethoven_-_Symphonie_5_c-moll_-_1._Allegro_con_brio.ogg'];
var idx=0;
var aud= document.getElementById('aud');
aud.src=urls[idx];
aud.addEventListener('ended', next); // for automatically starting the next.
function play(){
aud.play();
}
function pause(){
aud.pause();
}
function next(){
idx++;
if(idx === urls.length) idx=0;
aud.src = urls[idx];
aud.play();
}
<audio id = 'aud'></audio>
<button onclick="play();">play</button>
<button onclick="pause();">pause</button>
<button onclick="next();">next</button>

Related

Iframe Not Showing Random Videos

I am working on a script so that it fetches a random video and continuously keeps playing random videos back to back once the previous video is finished playing. It worked when I played the videos as mp4s in the video element, but when I rewrote the script to play them as embedded videos in an iframe, nothing shows up at all.
I just cannot seem to make it work. Any help would be greatly appreciated.
Thanks in advance.
<iframe class="frame" src="" width="640" height="360"></iframe>
<script>
var lastVideo = null;
var selection = null;
var player = document.getElementsByClassName("frame")[0]; // Get video element
var playlist = ["https://www.youtube.com/embed/qXYb8R3_B0k", "https://www.youtube.com/embed/Gi1P6UFTioQ", "https://www.youtube.com/embed/l_pR5obOwss"]; // List of videos
player.autoplay = true;
player.addEventListener("ended", getRandomUrl); // Run when video ends
function getRandomUrl(player) {
while (selection == lastVideo) { // Repeat until different video is selected
selection = Math.floor(Math.random() * playlist.length);
}
lastVideo = selection; // Remember last video
player.src = playlist[selection]; // Location of new video
}
getRandomUrl(player); // Select first video
player.play(); // Start video
</script>
I would guess that your eventListener for "ended" never triggers because a video is never started in the first place.
The solution in this case would be set a random video to the src attribute as the default and then the eventListener takes care of the rest.

Adding a video to a playlist using the Youtube Player IFrame API

I'm working on some kind of Youtube remote web application using the Youtube Player IFrame API and got stuck when I tried to use the built-in playlist system as the queue for the application.
Using the API, you are able to load a specific list of videos as a playlist with e.g.:
player.loadPlaylist({playlist: ['_9IBbMW2o_o']})`
But there is no function such as:
player.addVideoToPlaylist('_9IBbMW2o_o')
What I'm trying to do is adding a video without stopping or reloading the current playlist.
Is there a workaround or am I missing something?
By getting a little creative, we can actually use loadPlaylist() without causing any interruption. The API provides events, one of which will reveal itself to be useful to our purpose: onStateChange.
onStateChange
This event fires whenever the player's state changes. The data property of the event object that the API passes to your event listener function will specify an integer that corresponds to the new player state. Possible values are:
-1 (unstarted)
0 (ended)
1 (playing)
2 (paused)
3 (buffering)
5 (video cued)
Some observation shows that the -1 event fires when a playlist transitions from one video to another. This is our opportunity. By updating the playlist only when a transition happen, there is no (well, a barely) noticeable interruption.
The idea is to maintain a separate playlist, that we can manipulate. It's a simple array of Youtube videos identifiers, in which we can push new data whenever we want.
Everytime a video transition happens, we check the length of our playlist against the length of the player's playlist. If they do no match, we update the player's playlist.
We also keep track of the index, within the player's playlist, of the last video played before the transition. When loading the new playlist, we provide previous index + 1, as to play the next video in the playlist rather than start from the beginning.
The reason we use previous index + 1 is because using the current index would return 0 if we updated while playing the last video, since the player would loop back to the first video.
I must point out this is designed purely for the case of appending new videos to the playlist. Editing the playlist in other ways would require more logic.
The working demo on JSFiddle.
HTML
<div id="player"></div>
<button id="button">queue 2 more videos</button>
CSS
div {
width:300px;
height:240px;
background-color: yellow;
}
JavaScript
var player;
var playlist = ['b_XKnkQZkOM','dnNt78eGjSM'];
var previousIndex = 0;
$(window).load(function(){
player = new YT.Player('player', {
height: '240',
width: '300',
playerVars : {
playlist: playlist.join(','),
},
events: {
onStateChange: function(event) {
/*
the video has changed
seize the opportunity to update the playlist without interruption
*/
if(event.data == -1 || event.data == 0) {
// get current video index
var index = player.getPlaylistIndex();
// update when playlists do not match
if(player.getPlaylist().length != playlist.length) {
// update playlist and start playing at the proper index
player.loadPlaylist(playlist, previousIndex+1);
}
/*
keep track of the last index we got
if videos are added while the last playlist item is playing,
the next index will be zero and skip the new videos
to make sure we play the proper video, we use "last index + 1"
*/
previousIndex = index;
}
}
}
});
});
$(document).ready(function() {
$('#button').click(function(){
playlist.push('ZVeaEl7nMWM');
playlist.push('YRBwXHowb6I');
});
});
Note that if you block youtube.com/api/stats (Adblock, etc), the event 0 is not fired at the end of a video.
I figured out a solution where you first load in the playlist, then you grab all of the videos id's from the playlist and add in any new videos to an entirely new playlist.
var playlist = player.getPlaylist();
var newPlaylist = [];
for (var i = 0; i < playlist.length; i++) {
newPlaylist.push(playlist[i]);
}
newPlaylist.push('M7lc1UVf-VE');
player.loadPlaylist({playlist: newPlaylist});
Here is a jsfiddle example
I wasn't able to find anything in Youtube's IFrame API documentation to add a standalone video into a playlist.

Play multiple audio files in a slider

I'm trying to use this slider: http://tympanus.net/codrops/2012/06/05/fullscreen-slit-slider-with-jquery-and-css3/ but want to play a different audio file, each time the slide loads.
The way I imagine it working, is for the user to click play on the first slide, the audio to finish playing, then for the slide to change and it automatically plays the next audio file and so it continues until all slides are played through.
I've gotten it to the point where the slider changes when the audio has stopped, but cannot figure out how to play the next audio file, one after the other.
I'm very new to jQuery and am struggling a lot. Any help would really be appreciated!
Here is my work in progress: http://dailycrow.me/actualsite/
Thank you.
What I would do is to handle the audio playing with an scripting language such as PHP and call the needed method with parameters with Javascript or JQuery.
You can embed HTML with PHP so the audio can be played. Something like this:
$audioFile = "wishedAudioFile.mp3";
echo '<embed src="'.$audioFile.'" hudden="true" autostart="true"></embed>';
you can maintain an array of sources, where each index refers to a slide index, and from looking at this doc, you can use the onAfterChange event, code would be something like:
var audio = new Audio(), audSrcList = [
'slide1.wav',
'slide2.wav',
'slide3.wav',
'slide4.wav'
...
];
function afterSlideChange(slide, index){
audio.src = audSrcList[index];
audio.play();
};
...
$.Slitslider.defaults = {
...
// callbacks
onBeforeChange : function( slide, idx ) { return false; },
onAfterChange : afterSlideChange //CHANGED here
};

How to stop an audio from playing in JavaScript

Sorry about the confusing title, but I have the following problem. I am working on a site where people can press a link and play a song, but in a page where there are multiple links (for playing songs), users can press all the links and all the songs start to play at the same time. So, this makes the current selected song difficult to hear.
So, what I am trying to do is, to cancel / stop the last playing song when a new link is pressed. Here is my code:
<div class='content'>
click <a href="javascript:play_wav('h');" class='h play-audio'> here </a>
to play the song
</div>
function play_wav(audio_name)
{
var src = document.querySelector('.'+audio_name).innerHTML =
"<audio src='audio/"+classs+".wav' class='audio_"+audio_name+"'>";
document.querySelector('.audio_'+audio_name).play();
}
Don't mind the bad quality, but as you can see, when the link is pressed, the DOM integrates an <audio src='audio/foo.wav' class='audio_foo"'>
then the script finds the audio_foo class and plays the songs.
But when another link is pressed, how do I reset the DOM to it's original state or just stop it from playing a previously started song?
You can keep a reference to the currently playing song.
var current_audio;
function play_wav(audio_name)
{
if (current_audio)
{
current_audio.stop();
}
var src = document.querySelector('.'+audio_name).innerHTML = "<audio src='audio/"+classs+".wav' class='audio_"+audio_name+"'>";
current_audio = document.querySelector('.audio_'+audio_name);
current_audio.play();
}
I've never used audio in javascript before, but I'm assuming there is a stop function if there is a play function.
Hope this helps!
Something like this:
function play_wav(audio_name) {
// List of all audio tags
var audios = document.querySelectorAll('audio')
//Iterate over all
for (var i = 0; i < audios.length; i++) {
var audio = audios[i]
// Stop playing
audio.pause()
// Remove node
audio.parentNode.removeChild(audio)
}
var audio = document.querySelector('.'+audio_name)
audio.innerHTML = "<audio src='audio/"+classs+".wav' class='audio_"+audio_name+"'>"
audio.querySelector('audio').play()
}

auto pause mediaelement.js audio player when playing new track

using the mediaelement.js audio - Does anyone know how or if it's possible to have 1 track pause automatically when another is played when there are 2 or more audio tracks on the same page? (I guess like a play/pause toggle attribute)
there's an example of what I'm talking about here using a flash player: http://stockmusicboutique.com/background but was wondering if it would be possible with this html 5 player.
You could do something like this:
<audio src="track1.mp3" />
<audio src="track2.mp3" />
<script type="text/javascript">
// make an array for the mediaelement players
mediaElementPlayers = new Array();
// run mediaelement.js
$(document).ready(function(){
$('audio').mediaelementplayer({
success:function(mediaElement, domObject){
// add this mediaelement to the mediaElementPlayers array
mediaElementPlayers.push(mediaElement);
// bind the play event to the pauseAllPlayers function
mediaElement.addEventListener('play', function(e){
pauseAllPlayers(e.target); }
)
}
})
})
// iterate through the mediaElementPlayers array, pause all players except the one that triggered the event.
function pauseAllPlayers(currentPlayer){
for(i=0; i<mediaElementPlayers.length; i++){
if(mediaElementPlayers[i] != currentPlayer){
mediaElementPlayers[i].pause();
}
}
}
</script>

Categories