Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Audio tag on Safari has a delay

Tags:

I'm trying to accomplish a simple doodle-like behaviour, where a mp3/ogg sound rings on click, using the html tag. It is supposed to work under Firefox, Safari and Safari iPad is very desireable.

I've tried many approaches and have come down to this:

HTML

    <span id="play-blue-note" class="play blue" ></span>     <span id="play-green-note" class="play green" ></span>       <audio id="blue-note" style="display:none" controls preload="auto" autobuffer>          <source src="blue.mp3" />         <source src="blue.ogg" />         <!-- now include flash fall back -->     </audio>      <audio id="green-note" style="display:none" controls preload="auto" autobuffer>          <source src="green.mp3" />         <source src="green.ogg" />     </audio> 

JS

function addSource(elem, path) {     $('<source>').attr('src', path).appendTo(elem); }  $(document).ready(function() {       $('body').delegate('.play', 'click touchstart', function() {         var clicked = $(this).attr('id').split('-')[1];          $('#' + clicked + '-note').get(0).play();        });  });   

This seems to work great under Firefox but Safari seems to have a delay whenever you click, even when you click several times and the audio file has loaded. On Safari on iPad it behaves almost unpredictably.

Also, Safari's performance seems to improve when I test locally, I'm guessing Safari is downloading the file each time. Is this possible? How can I avoid this? Thanks!

like image 274
Nacho Avatar asked Mar 21 '12 19:03

Nacho


People also ask

Does HTML5 support audio tag?

HTML5 <audio> Tag. Since the release of HTML5, audios can be added to webpages using the “audio” tag.

What is the correct HTML 5 element for playing audio files?

The HTML <audio> element is used to play an audio file on a web page.

Is audio tag deprecated?

The <bgsound> HTML element is deprecated. It sets up a sound file to play in the background while the page is used; use <audio> instead. Warning: Do not use this!

What is the HTML 5 element for adding audio to a web page?

<audio>: The Embed Audio element.


1 Answers

On desktop Safari, adding AudioContext fixes the issue:

const AudioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext(); 

I found out by accident, so I have no idea why it works, but this removed the delay on my app.

like image 144
Jaakko Karhu Avatar answered Sep 22 '22 17:09

Jaakko Karhu