Reputation: 11773
I've got a web app that needs to play a handful of sounds. The app is intended primarily for mobile devices. As it stands I'm creating an <audio>
element for each sound I need and triggering the play()
method of each with javascript. I'd prefer to have all the sounds in one audio element, each being a different source, something along the line of:
<audio controls="controls" preload="auto" id="audioPlayer">
<source src="click1.ogg" type="audio/ogg" />
<source src="click2.ogg" type="audio/ogg" />
</audio>
and trigger each source by calling something like .play("click1.ogg")
.
I can't afford to change the source with javascript and wait for the new source to load; the sounds need to be loaded with the page.
Is there a solution similar to what I've written above or should I stick with different audio elements for different sounds?
As a secondary question, am I taking a performance hit by defining multiple audio elements?
Upvotes: 3
Views: 3937
Reputation: 5182
I up voted mic because it is a good answer! Here is an example of how I did what he suggested.
http://jsfiddle.net/earlonrails/tTF89/6/
html
<audio controls="controls" width="300px" id="audioPlayer">
<!-- load broken audio -->
<source type="audio/mpeg" src="http://www.google.com/4/0/4" />
</audio>
javascript
var urlOne = 'http://www.tonycuffe.com/mp3/tail%20toddle.mp3',
urlTwo = 'http://freeplaymusic.com/search/download_file.php?id=4&dur=0&type=mp3';
function attrs(element, attributes) {
for (var prop in attributes) {
element.setAttribute(prop, attributes[prop]);
}
}
function reloadAudioTag(path, player, holder) {
if (player) player.parentNode.removeChild(player);
var player = document.createElement('audio'),
source = document.createElement('source');
source.type = "audio/mpeg"
attrs(player, {
"width": "300px",
"controls": "controls",
"autoplay": "autoplay",
"id": 'audioPlayer'
});
player.appendChild(source);
if (holder) {
holder.insertBefore(player, holder.childNodes[0]);
} else {
document.body.appendChild(player);
}
source.src = path;
player.load();
return player;
}
console.log("called!");
reloadAudioTag(urlOne, document.getElementById("audioPlayer"));
console.log("Still going!");
setTimeout(function () {
reloadAudioTag(urlTwo, document.getElementById("audioPlayer"));
console.log("Finished!");
}, 5000);
Upvotes: 0
Reputation: 9202
You should use different audio elements. The source tags in the audio element are made because of browser and system compatibility. It will automatically select the format which is provided by browser and system (ogg, mpeg, avi or wmv).
To your second question... You aren't taking a performance hit because just one source of all sources in the audio element will be loaded.
Upvotes: 2