javascript - Delay in playing HTML5 audio file on mobile browsers -
i making web app, , needed add short sound when button being clicked.
the file in mp3 format , around 24kb in size, didnt want use javascript create element added dom , used css hide it, added preload="auto" gets loaded dom
<audio id="click" preload style="display:none;"> <source src="sound/click.mp3" type="audio/mp3"> </audio>
in javascript, have like:
var clicksound = $('#click')[0];
then in function listens click on button have:
function(){ clicksound.play(); }
this works fine on computer (firefox, chrome), on mobile after clicking trigger button, wait 3 seconds before plays first time, , will play instantly after first delayed play.
update:
i noticed if navigate mp3 file on mobile http://example.com/sound/click.mp3 , click on play, still delays, seems had buffer.
anyway around problem?
complete example:
var clicksound = document.getelementbyid('click'); var play = document.getelementbyid('play'); play.addeventlistener('click', function() { clicksound.play(); }, false);
<audio id="click" preload> <source src="http://scriveit.com/sound/click.mp3" type="audio/mp3"> </audio> <input id="play" type="button" value="play sound">
one way of doing smaller audio files pre-loading file blob:
<button>play</button> <audio></audio> <script> var xhr = new xmlhttprequest(); xhr.open('get', 'click.mp3', true); xhr.responsetype = 'blob'; var audio = document.queryselector('audio'); xhr.onload = function () { audio.src = url.createobjecturl(xhr.response); }; xhr.send(); document.queryselector('button').onclick = function () { audio.play(); }; </script>
please note requires xhr2 (http://caniuse.com/#feat=xhr2) , blob urls (http://caniuse.com/#feat=bloburls) , same origin policy applies here. moreover, should make sure file sent strong caching headers prevent clients reloads file every request.
edit: approach using data urls (see http://jsfiddle.net/apo299od/):
<button>play</button> <audio></audio> <script> var audio = document.queryselector('audio'); audio.src = 'data:audio/mp3;base64,suqzbaaaaaa...'; document.queryselector('button').onclick = function () { audio.play(); }; </script>
the disadvantages here harder maintain , inflate response size 33%.
Comments
Post a Comment