I have a webpage that shows pictures. Upon clicking on a picture, I would like it to play some sound file (an audio recording of the name of the object in the picture). I have working code for this, but there's a noticeable delay between clicking on the image, and hearing the audio file being played. How can I improve my code to get rid of that delay?
HTML:
<div>
<button style="background-image:url('objects/images/horlicks.JPG'); width:480; height:640" onclick="changeText('horlicks', 'Horlicks', 'objects/sounds/horlicks.mp3')">
</button>
<p id="horlicks"></p>
</div>
JavaScript:
function changeText(id, newText, audioFile) {
document.getElementById(id).innerHTML = newText; // This happens quickly
new Audio(audioFile).play(); // This takes a long time
}
Update:
The HTML/JavaScript have been updated to look like this, and there is still a lag while playing the audio file (though the lag is only noticeable on the iPad and not on my laptop):
<div>
<button style="background-image:url('objects/images/horlicks.JPG'); width:480; height:640" onclick="changeText('horlicks', 'Horlicks', '32'); horlicks.play();">
</button>
<p id="horlicks"></p>
</div>
JavaScript:
var horlicks = new Audio('objects/sounds/horlicks.mp3');
function changeText(id, newText, size) {
document.getElementById(id).innerHTML = '<font size="'+size+'">'+newText+"</font>";
}