javascript - Dynamically created HTML5 audio is not playable in some browsers? -


i creating audio element in javascript , appending document. controlling through javascript well. works fine in firefox, chrome, , opera not on ie , safari. in 2 browsers, readystate of audio element never changes 0 nor associated events fire. here basic program:

var init = function() {     var audioelement = createaudioelement();             audioelement.addeventlistener('canplay', function() {         audioelement.play();         trace(audioelement.readystate);     }, false);     document.body.appendchild(audioelement);     //audioelement.play();   }  var createaudioelement = function() {     var m4a = 'song.m4a';     var ogg = 'song.ogg';      var m4asrc = document.createelement('source');         m4asrc.setattribute('src', m4a);         m4asrc.setattribute('type', 'audio/mp4');     var oggsrc = document.createelement('source');         oggsrc.setattribute('src', ogg);         oggsrc.setattribute('type', 'audio/ogg');     var audioele = document.createelement('audio');         audioele.setattribute('preload', 'preload');         audioele.appendchild(m4asrc);         audioele.appendchild(oggsrc);      return audioele; } 

i know bit late, still; managed play audio on browsers (except ie < 9) without appending dom. can create audios this:

var audios = {}; audios['audioidorname'] = new audio('pathtoyouraudio');   // create audio element audios['audioidorname'].load();                           // force load audios['audioidorname'].addeventlistener('canplaythrough', audioloaded, false); // add event when audio loaded 

then create audioloaded() function checks when audios loaded (if instance added more 1 in loop or 1 after another.

var audiosloaded = 0 function audioloaded(){      audiosloaded++;     console.log("loaded "+this.src);     // here can check if number of audios loaded and/or remove eventlistener canplaythrough     audios['audioidorname'].removeeventlistener('canplaythrough', audioloaded, false);        } 

then manipulate audios these functions:

audios['youraudioidorname'].pause(); audios['youraudioidorname'].currenttime = 0; // pause() , currenttime = 0 imitate stop() behaviour doesn't exist ... audios['youraudioidorname'].play(); 

this worked me.

you can try appending audio element existing element if insist on appending dom. see more details here.

unfortunately there still many other issues html5 audio considering cross-browser usage. codecs 1 thing; using ogg+mp3 necessary. flash fallback not-so-neat solution used libraries/apis such soundmanager , howler.js. there soundjs may best thing try. see question well.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -