Monday 15 April 2013

javascript - Playing Audio Using Jquery -



javascript - Playing Audio Using Jquery -

i have little jquery function play sound when user clicks link. don't need controls, short samples. want play anytime user clicks. here html section should play;

</div class="classicalrecordings"> <a href="#" class="play" data-audio-src="music/classical/open.mp3">open song</a> </div>

then jquery play sound;

function playmusic(){ var audioelement = document.createelement('audio'); var audioelementsrc = $(this).attr('data-audio-src'); audioelement.setattribute('src', audioelementsrc); $.get(); audioelement.addeventlistener("load", function(){ audioelement.play(); }, true); } $(function(){ $('.play').click(playmusic); });

it doesn't seem work. think has src variable, not sure passing audioelement correctly. have tested using alert sure grabbing data-audio-src correctly. help appreciated.

i think event you're looking loadeddata event.

function playmusic(){ var audioelement = document.createelement('audio'); var audioelementsrc = $(this).attr('data-audio-src'); audioelement.setattribute('src', audioelementsrc); $.get(); // changed "load" t0 "loadeddata" audioelement.addeventlistener("loadeddata", function(){ audioelement.play(); }, true); } $(function(){ $('.play').click(playmusic); });

although improve off having static sound element , changing src attribute on user clicks rather creating new sound element.

// illustration var sound = document.getelementsbytagname('audio')[0]; audio.addeventlistener('loadeddata', function() { this.play(); }, true); function playmusic() { var audioelementsrc = $(this).attr('data-audio-src'); audio.setattribute('src', audioelementsrc); }; $('.play').click(playmusic);

there framework worth checking out. listenjs. wrote :)

javascript jquery html audio

No comments:

Post a Comment