javascript - Using JQueryUI as an audio Seek control, and rebinding a new slider to the same <audio> control when a song is changed -


thank looking @ question. fiddle here.

i trying implement audio player many songs on page. using jqueryui slider , html5 audio, 1 audio element , multiple sliders.

the problems right are:

  1. the slider not animate audio.
  2. the slider not seek audio.
  3. previously, when both of above working, once chose spot in song, slider no longer animate.

i have created function rebindslider() when new song clicked. inside function, 2 things happen: a) new slider created, slide , stop listeners defined, , b) new slider bound timeupdate event on audio element new song. feel should need, slider not bind, , undefined error can seen when try drag slider.

using single slider, , single audio element, have gotten 90% way there; introduced multiple divs sliders though, problems started occurring.

here code rebindslider:

function rebindslider(sliderdiv) {   var createseek = function() {     sliderdiv.slider({       value: 0,       step: 1,       orientation: "horizontal",       range: "min",       max: audioplayer.duration,       animate: true,        slide: function() {         manualseek = true;       },        stop: function(e, ui) {         manualseek = false;         audioplayer.currenttime = ui.value;       }     });   };    createseek();    $(audioplayer).bind('timeupdate', function() {     if (!manualseek) {       sliderdiv.slider('value', audioplayer.currenttime);     }   }); }  

further description below.

there list of songs included on page. each song has containing div, within <a> contains meta data (absent in fiddle), div designated audio seek slider. there single audio element on page, has source re-loaded click through songs.

when song clicked, destroy sliders bound playing audio (if necessary), , bind new slider clicked song audio player.

the closest have gotten have slider 1) begin animating when song plays 2) dragging of slider moved different position in song. once slider had moved though, no longer animated. after refactor, slider no longer works, , though go previous commit working code, refactor drastic prefer present current, non-working code, better represents end with.

reasoning, , additional information.

i making web app, have concept audio player rather build myself modify have come across. being said, if know of can implement, love suggestions.

the idea sounds simple enough, , of done, there crucial part of having trouble with, setting slider animate with, , seek desired spot in audio track, , able rebind new slider audio when song clicked.

there few changes needed slider working correctly. i'll cover them each, in order apply.

invalid slider max value

the first issue slider's max value set audioplayer.duration, , good, except html5 audio player loads audio assets asynchronously. means though might have loaded audio prior setting slider, audio asset may not loaded yet, , audioplayer.duration may invalid (likely nan).

simply remove max key (and value) slider initialization, , work. et viola! slider moves!

one caveat: slider defaults max value of 100 units, , duration of audio little on 25 seconds, song finishes playing when slider 1/4th of way along. can set max key 25 (seconds), that's little inelegant, , wont work if change audio use different source.

set slider max value

capturing audioplayer.duration must done handling event, once asynchronous load has completed. javascript provides such event: onloadedmetadata. let's install event handler, , make work:

audioplayer.onloadedmetadata = function() {     $(".slider").slider("option", { max: math.floor(audioplayer.duration) }); }; 

now, set slider's max audioplayer.duration once audio asset has loaded. actually, setting max value of sliders, shouldn't problem, since they're hidden. if have large number of songs, there might bit of delay, , may want find specific slider update.

smooth sliding

now, may notice after these changes slider jumpy. pauses second, jumps, pauses, etc. can fixed easily, changing step key 0.1 in slider initialization, so:

sliderdiv.slider({   value: 0,   step: 0.1,   orientation: "horizontal", 

the time updates occur every 50 250 milliseconds, slider move in 1-second increments. now, 1/10th of second increments, slider move more smoothly. can decrease if like, don't make number small; 0.01 practical lower bound.

update end-of-play state

when song has finished, "play" button left in play state, though there's no longer playing. there's event that, well: onended. we'll use event update ui, user doesn't confused:

audioplayer.onended = function() {   playbutton.removeclass('fa-pause-circle-o');   playbutton.addclass('fa-play-circle-o'); }; 

now, when song finishes, play button go "play" state, , user know clicking on play song.

refactor play button state

since there 3 places update state of play button, , involves duplication, can refactor state handling. function definitively set state of play button:

function setuistate() {   if (audioplayer.paused || audioplayer.ended) {     playbutton.removeclass('fa-pause-circle-o');     playbutton.addclass('fa-play-circle-o');   } else {     playbutton.removeclass('fa-play-circle-o');     playbutton.addclass('fa-pause-circle-o');   } } 

now, calling other functions, end onended event handler:

audioplayer.onended = function() {   setuistate(); }; 

the changeui function:

function changeui(selectedsong) {   setuistate();    var sliderdiv = selectedsong.parent().find('.slider');   rebindslider(sliderdiv);//bind desired slider   $('.slider').hide(); //hide sliders   sliderdiv.show();//show desired slider }  

and, play button click handler:

$(".playbutton").click(function() {       if (audioloaded === true) {     if (!audioplayer.paused) {       audioplayer.pause();     } else {       audioplayer.play();     }     setuistate();   } else {     alert("please click song");   }   return false; }); 

this makes ui state management button simple deal with, , keeps state creeping out through app. can see how refactored code noticeable clearer , easier maintain. plus, bonus, got use cool audioplayer.ended attribute, don't see used much.

but wait, there's more!

with changes above, you're on way having functional audio player. that's not end of line feature functionality. there's room grow!

i've create jsfiddle includes of these changes, few other mods original code. can find recent version at: https://jsfiddle.net/mgaskill/mp087adp/. additional features keep popping up, jsfiddle includes these additional features:

  • volume control (slider)
  • time display
  • dynamically generated html audio controls (keeps html simpler)

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -