preload next song before end of the current song - javascript

i have one issue related jplayer. i am using jplayer for play song in my site right now i am fetching song using ajax call and add that song into jplayer playlist and now its working fine
my question is is there any option to ready next song before end of current song because when i try it with less then 1 minute song its working fine but when i have each song duration more then 4 minutes its take 3 to 4 seconds to load new song
this is my code for load song in jpalyer playlist
// for create jplayer and add song in playlist
function play_music(songobj) {
is_play = 1;
// $("#jquery_jplayer_1").jPlayer("destroy");
var playlist_length = songobj.length;
myPlaylist = new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_N"
},songobj, {
playlistOptions: {
enableRemoveControls: true,
autoPlay: true
},
supplied: "oga, mp3",
wmode: "window",
useStateClassSkin: true,
autoBlur: false,
smoothPlayBar: true,
keyEnabled: true,
ended : function(){
if(playlist_length == currlength){
// alert('end playlist');
is_play = 0
location.reload();
}
else{
/*if( == ){
console.log('yesssssss');
}*/
// console.log(play_index[index_key]);
// console.log(playlist_obj[currlength]);
loop = 1;
currlength += 1;
var songindex = song_index[currlength - 1];
var listindex = playlist_obj[index_key];
if(song_index[currlength - 1] == playlist_obj[index_key]){
index_key += 1;
$("#jquery_jplayer_1").jPlayer("pause", 0);
console.log('playlist over start next');
setTimeout(function() {
$("#jquery_jplayer_1").jPlayer("play", 0);
}, $('#timeout').val()*1000);
}
}
},
});
}
also if there are any options for preload all song before play, please guide me this is very important for me
thanks

Behind the scenes their is only one audio source even for playlist. jPlayer & jPlaylist are just wrappers.
This means that you can't load the next song before the current ends because that would require changing the audio source which would change the song.
Their is no built in way to do this. Maybe their is a way such as having another hidden jPlayer on the page and load the next song and somehow copying the data over without having to load but I am not sure and you probably shouldn't even have to do this.
3-4 seconds to load seems weird though, it should only load the metadata as default and in the below example for a 5 min+ song it's 46KB...
Maybe their is something wrong with your .mp3, .ogg urls. Can you post them?
This loads instantly for example:
http://jsfiddle.net/Ls8p90y9/175/
$("#jquery_jplayer_1").jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
title: "Bubble",
mp3: "http://www.jplayer.org/audio/mp3/Miaow-01-Tempered-song.mp3"
});
},
timeupdate: function(event) {
$("#jp_container_1 .jp-ball").css("left",event.jPlayer.status.currentPercentAbsolute + "%");
},
supplied: "mp3",
});
Try messing with the preload option:
preload
String : (Default: "metadata") : Valid values are "none", "metadata" and "auto", which matches the HTML5 draft standard. Use "auto" to preload the file.
Preload is a hint to the user agent, not a command. Some browsers ignore this option.

Related

How can I make an audio sound play only once using JQuery?

So I have a div that plays an mp3 sound when it is clicked. Instead of playin once. It continues to play over and over again. The snippet of code is:
$(".g-contain").click(function() {
audioElement.play();
});
This may be irrelevant but I figure I should show you the overall code:
/* set no cache */
$.ajaxSetup({ cache: false });
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'https://www.dropbox.com/s/k8xaglyd48vbnq1/pacman_chomp.mp3?dl=1');
audioElement.addEventListener('ended', function() {
this.play();
}, false);
$.getJSON("scripts/data", function(data) {
var html = [];
/* loop through array */
$.each(data, function(index, g) {
$(".container").append(
"<div class='g-details'><div class='name'>" +
g.name + "</div>);
// And finally my click call is here
$(".g-contain").click(function() {
audioElement.play();
});
Not sure why the mp3 file keeps playing when g-contain div is clicked
It's due to this code:
audioElement.addEventListener('ended', function() {
this.play();
}, false);
You attached an event listener to the audio element to re-play when the playing is ended. So once it's played (with click) it will play infinitely.
From the MDN ended event Reference:
ended
The ended event is fired when playback or streaming has stopped
because the end of the media was reached or because no further data is
available.
Just get rid of this code.

Video starts when current slide // Superslides

So I solved the individual slide delay problem with superslides using the answers found at Individual slide delay // Superslides, but now I'm having trouble with a video I put in.
The video is Slide 4, but it starts playing when the slider loads. I'm using YTPlayer for the player.
jQuery('#fullscreen , .p-section').superslides({
play: 12000,
animation: 'fade',
inherit_height_from: window,
});
jQuery('#fullscreen').on('animated.slides', function () {
var slideNo = jQuery(this).superslides('current');
if(slideNo === 3){ //slide 4
jQuery(this).superslides('stop');
setTimeout(function(){
jQuery('#fullscreen').superslides('start')
}, 20000);
} });
That is what I have for the slider. How can I get the video to start playing only when the video is the current slide and then transitions to the next slide after it plays.
UPDATE: IN CASE SOMEONE WAS LOOKING FOR THIS AS WELL.
With the help of #Sunand, here's what I have.
jQuery('#fullscreen , .p-section').superslides({
play: 12000,
animation: 'fade',
inherit_height_from: window,
});
jQuery('#fullscreen').on('animated.slides', function () {
var slideNo = jQuery(this).superslides('current');
if(slideNo === 3){ //slide 4
jQuery(this).superslides('stop');
jQuery(".mb_YTVPBar .buttonBar").css({"display":"block"});
jQuery(".home-elements").css({"display":"none"});
jQuery("#bgndVideo").playYTP();
jQuery("#bgndVideo").on("YTPEnd",function(){
jQuery('#fullscreen').superslides('start');
jQuery(".mb_YTVPBar .buttonBar").css({"display":"none"});
jQuery(".home-elements").css({"display":"block"});
});
}
});
Now I'm still working on if they click next before the video is done, then the video should stop. Will update this when I figure it out.
set autoPlay:false in the data-property attribute and change ur code to
jQuery('#fullscreen').on('animated.slides', function () {
var slideNo = jQuery(this).superslides('current');
if(slideNo === 3){ //slide 4
var me = this;
jQuery(this).superslides('stop');
jQuery("#videoID").playYTP();
jQuery("#videoID").one("YTPEnd",function(){
jQuery(me).superslides('start');
});
} });

Update the JPlayer MP3 file each time a function is called

function showAudioFull(id)
{
var url = URL_DIRSCREENAUDIOSHOT+AUDIOSHOT_PREFIX+id+'.mp3';
var myCirclePlayer = new CirclePlayer("#jquery_audioFile",
{
m4a: url
}, {
cssSelectorAncestor: "#cp_container_1"
});
}
I am appending the MP3 link to JPlayer each time I call this function in my JS file.
There will be a set of images with "id". With an onClick() function this showAudioFull() is invoked.
But problem is JPlayer is not updating the mp3 file that is being played. It keeps playing the same audio which I click at the first time.
FYI : Using JPlayer Circle player
What about:
var myCirclePlayer = new CirclePlayer("#jquery_audioFile", {
m4a: url
}, {
cssSelectorAncestor: "#cp_container_1"
});
function showAudioFull(id) {
var url = URL_DIRSCREENAUDIOSHOT + AUDIOSHOT_PREFIX + id + '.mp3';
myCirclePlayer("setMedia", {
mp3: url
});
};
This method (setMedia) is used to define the media to play. The media parameter
is an object that has properties defining the different encoding
formats and a poster image. Source: jPlayer dev guide

Keeping two YouTube videos in sync with each other

I've got two identical YouTube videos embedded on the same page. I'd like them to both be in sync, here are my requirements / notes:
Both videos must start at the same time
When a video is played / paused by the user the other video does the same
This is quite easy via the API
When one video buffers the other stops to wait, and starts when they are both ready
I only need audio from one video
Sync accuracy doesn't have to be millisecond perfect, just reliable
One video will be used as a background video
This video will be slightly blurred (using CSS3 blur), so quality not super essential
I've tried using the YouTube JS API to listen for player state changes and attempt to keep both videos in sync, however it wasn't as reliable as I'd hoped for. I'll post part of the code for this below.
One caveat is that one video will appear larger than the other, so the YouTube might provide a higher quality video for that.
Because I'm using CSS3 blur I can only use recent Webkit browsers, so a solution that works on these alone (and not FF/IE) is not a problem.
My question is this, for the requirements above, is there any way to keep these two videos in sync? I did consider if it was possible to use the canvas API to "redraw" the video, but after researching figured this wasn't going to be possible.
buffering = false;
var buffer_control = function(buffering_video, sibling_video, state) {
switch ( state ) {
case 1: // play
if ( buffering === true ) {
console.error('restarting after buffer');
// pause both videos, we want to make sure they are both at the same time
buffering_video.pauseVideo();
sibling_video.pauseVideo();
// get the current time of the video being buffered...
var current_time = buffering_video.getCurrentTime();
// ... and pull the sibling video back to that time
sibling_video.seekTo(current_time, true);
// finally, play both videos
buffering_video.playVideo();
sibling_video.playVideo();
// unset the buffering flag
buffering = false;
}
break;
case 3: // buffering
console.error('buffering');
// set the buffering flag
buffering = true;
// pause the sibling video
sibling_video.pauseVideo();
break;
}
}
Your project is kinda interesting, that's why I decided to try to help you. I have never used the youtube API but I have tried some coding and it might be a start for you.
So here is the code I have tried and it seems to work quite well , it certainly needs some improvements ( I haven't tried to calculate the offset between the two played videos but letting them unmute shows the mismatch and it sounds legit)
Here we go :
Let's start with some html basics
<!DOCTYPE html>
<html>
<head>
We add an absolute positionning for the foreground player so it overlays the one playing the background video (for testing)
<style>
#player2{position:absolute;left:195px;top:100px;}
</style>
</head>
<body>
jQuery is used here to fade in/out the players (you'll see why below) but you can use basic JS
<script src="jquery-1.10.2.min.js"></script>
The < iframes> (and video players) will replace these < div> tags.
<div id="player1"></div> <!-- Background video player -->
<div id="player2"></div> <!-- Foreground video player -->
<script>
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);
This function creates the < iframes> (and YouTube players) after the API code downloads. Note the callback functions : onPlayer1Ready and onPlayer1StateChange
var player1;
var player2;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player1', {
height: '780',
width: '1280',
videoId: 'M7lc1UVf-VE',
playerVars: { 'autoplay': 0, 'controls': 0 },
events: {
'onReady': onPlayer1Ready,
'onStateChange': onPlayer1StateChange
}
});
player2 = new YT.Player('player2', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayer2Ready,
'onStateChange': onPlayer2StateChange
}
});
}
var player1Ready = false;
var player2Ready = false;
So now is the interesting part of the code. The main issue in your project of sync is linked to the fact that videos need to be buffered before launching them. Actually the API doesn't provide any kind of intuitive function to preload the videos (due to bandwidth issues (client and server side). So we have to get a bit tricky.
The steps to preload a video are the following:
Hide the player so the next steps aren't visible for the user);
Mute the player ( player.mute():Void );
Emulate a jump in timeline to start the buffering ( player.seekTo(seconds:Number, allowSeekAhead:Boolean):Void );
Wait for a state change event equal to YT.PlayerState.PLAYING;
Pause the video ( player.pauseVideo():Void );
Rewind the video with player.seekTo(seconds:Number, allowSeekAhead:Boolean):Void ;
Unmute the player ( player.unMute():Void );
Show the player.
You have to preload your two videos.
var preloading1 = false;
var preloading2 = false;
The API will call these functions when the video players are ready.
function onPlayer1Ready(event)
{
player1Ready = true;
preloading1 = true; // Flag the player 1 preloading
player1.mute(); // Mute the player 1
$( "#player1" ).hide(); // Hide it
player1.seekTo(1); // Start the preloading and wait a state change event
}
function onPlayer2Ready(event) {
player2Ready = true; // The foreground video player is not preloaded here
}
The API calls this function when the background video player's state changes.
function onPlayer1StateChange(event)
{
if (event.data == YT.PlayerState.PLAYING ) {
if(preloading1)
{
prompt("Background ready"); // For testing
player1.pauseVideo(); // Pause the video
player1.seekTo(0); // Rewind
player1.unMute(); // Comment this after test
$( "#player1" ).show(); // Show the player
preloading1 = false;
player2Ready = true;
preloading2 = true; // Flag for foreground video preloading
player2.mute();
//$( "#player2" ).hide();
player2.seekTo(1); // Start buffering and wait the event
}
else
player2.playVideo(); // If not preloading link the 2 players PLAY events
}
else if (event.data == YT.PlayerState.PAUSED ) {
if(!preloading1)
player2.pauseVideo(); // If not preloading link the 2 players PAUSE events
}
else if (event.data == YT.PlayerState.BUFFERING ) {
if(!preloading1)
{
player2.pauseVideo(); // If not preloading link the 2 players BUFFERING events
}
}
else if (event.data == YT.PlayerState.CUED ) {
if(!preloading1)
player2.pauseVideo(); // If not preloading link the 2 players CUEING events
}
else if (event.data == YT.PlayerState.ENDED ) {
player2.stopVideo(); // If not preloading link the 2 players ENDING events
}
}
The API calls this function when the foreground video player's state changes.
function onPlayer2StateChange(event) {
if (event.data == YT.PlayerState.PLAYING ) {
if(preloading2)
{
//prompt("Foreground ready");
player2.pauseVideo(); // Pause the video
player2.seekTo(0); // Rewind
player2.unMute(); // Unmute
preloading2 = false;
$( "#player2" ).show(50, function() {
Here is a part of the code that acts strangely. Uncommenting the line below will make the sync quite bad,but if you comment it, you will have to click twice on the PLAY button BUT the sync will look way better.
//player2.playVideo();
});
}
else
player1.playVideo();
}
else if (event.data == YT.PlayerState.PAUSED ) {
if(/*!preloading1 &&*/ !preloading2)
player1.pauseVideo();
}
else if (event.data == YT.PlayerState.BUFFERING ) {
if(!preloading2)
{
player1.pauseVideo();
//player1.seekTo(... // Correct the offset here
}
}
else if (event.data == YT.PlayerState.CUED ) {
if(!preloading2)
player1.pauseVideo();
}
else if (event.data == YT.PlayerState.ENDED ) {
player1.stopVideo();
}
}
</script>
</body>
</html>
Note that the views might not be counted with this code.
If you want the code without the explanations you can go here : http://jsfiddle.net/QtBlueWaffle/r8gvX/1/
2016 Update
Live Preview
Hope this helps.

youtube API functions just stopped working

I am making a web app based on Youtube AS3 APIs. Everything was going well and now suddenly all my player functions have stopped working. No event apart from "onYouTubePlayerAPIReady" is being called.
I have buttons to control the volume of the video now the give me the error" player.getVolume() is not a function". I am able to sucessfully load a video and play it, but nothing more.
var h = ($("#ytplayer").width()*(9/16));
player = new YT.Player('ytplayer', {
height: h,
videoId: currentlyPlaying,
playerVars: {
wmode: 'opaque',
autoplay: '1',
vq: 'small',
controls: '0',
iv_load_policy: '3',
rel: '0'
},
events: {
'onStateChange': onPlayerStateChange
}
});
makeControlsLive();
function makeControlsLive(){
/*Make controls live*/
logThis("Making ocntrols live now...");
$("#vol_up").click( function(){
if(player){
var currentVol = player.getVolume();
if((currentVol+10) <= 100){
player.setVolume(currentVol+10);
$("#vol_value").text((currentVol+10)+"%");
$("#vol_mute").text(" mute ");
}
}
});
$("#vol_down").click( function(){
if(player){
var currentVol = player.getVolume();
if((currentVol-10) >= 0){
player.setVolume(currentVol-10);
$("#vol_value").text((currentVol-10)+"%");
}
}
});
$("#vol_mute").click( function(){
if(player){
if(player.isMuted()){
$("#vol_mute").text(" mute ");
player.unMute();
}
else{
$("#vol_mute").text(" unmute ");
player.mute();
}
}
});
}
function onPlayerStateChange(newState) {
alert(player.getPlayerState());
}
Has someone faced a simialr problem ? Is there a chance there is a bug with the youtube servers ?
I have this problem my code was working perfectly for month and then a few days ago it just stopped and the seek to function to loop the video again just doesn't work anymore my bet is google has messed around with it the youtube api team has a reputation for changing things without announcing the change and leave little documentation on new changes as of yet i have no idea how to fix it and it seem no one else does either but code doesn't just break over night they have obviously changed something.

Categories