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!
HTML5 <audio> Tag. Since the release of HTML5, audios can be added to webpages using the “audio” tag.
The HTML <audio> element is used to play an audio file on a web page.
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!
<audio>: The Embed Audio element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With