I have a problem where I can play an audio file if it is added directly to the html5 source code as the src attribute, but it doesn't play if I try to set the src at runtime.
Originally I had the following piece of HTML containing a few audio tags:
<audio id="audio1" controls preload="none" src="http:/theurl/clip1.mp3"></audio>
<audio id="audio2" controls preload="none" src="http:/theurl/clip2.mp3"></audio>
With the clips being played with the following function that gets called with the id and clip url:
function audioClick(id, clip) {
var audio = document.getElementById(id);
if (audio.paused) {
audio.play();
}
else {
audio.pause();
audio.currentTime = 0;
}
}
This works and when the user clicks on the relevant part of the page the appropriate audio file plays, however the problem is that the browser takes about 3-4 seconds to load the page which is too long. I have tracked down the reason for the delay to be due to the src attribute being remote files. And setting preload to "none" or "metadata" doesn't do anything to speed things up.
So to workaround this I wanted to set the src at runtime, so changed the function to this:
function audioClick(id, clip) {
var audio = document.getElementById(id);
if (audio.paused) {
audio.setSrc(clip);
audio.load();
audio.play();
}
else {
audio.pause();
audio.currentTime = 0;
}
}
I tried setting the html to this
<audio id="audio1" controls></audio>
<audio id="audio2" controls></audio>
But there were two problems: 1) the audio doesn't play 2) the controls displays an initial message saying the file can't be played
I don't there to be a message in the controls saying the file can't be played so I changed the html to:
<audio id="audio1"></audio>
<audio id="audio2"></audio>
However the problem with the file not playing remains.
Why doesn't the audio file play when done this way?
setSrc
does not appear to be a method ofHTMLAudioElement
according to the W3C spec. Did you simply mean to set thesrc
property? – apsillers