HTML5 audio playback delay in mobile browsers

I am creating a web application and I need to add a short sound at the click of a button.

the file is in mp3 format and about 24kb in size, I did not want to use javascript to create the element, so I added it to the DOM and used CSS to hide it, and also added preload = "auto" to get the loaded DOM

<audio id="click" preload style="display:none;"> 
   <source src="sound/click.mp3" type="audio/mp3">
</audio>

in javascript, I have something like:

var clickSound = $('#click')[0];

then in the function that listens for even pressing the button, I:

function(){
  clickSound.play();
}

this works fine on my computer (firefox, chrome), but on a mobile phone after pressing the trigger button it will wait 3 seconds before it plays for the first time and will now play right after the first delayed playback.

Update:

, mp3 , http://example.com/sound/click.mp3 , , .

?

:

jsFiddle .

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">
Hide result
+4
1

- 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>

, XHR2 (http://caniuse.com/#feat=xhr2) URL- Blob (http://caniuse.com/#feat=bloburls), . , , , .

: - URL- (. 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>

, 33%.

+3

All Articles