Question: I have 2 audio sounds and I want to play one HTML5 audio element at a time.
Similar Post: Play one HTML audio element at a time.
I saw a similar post to my question. However, as a JavaScript beginner I did not understand the code. So I tried a simpler way so I can understand, but is not working. I would appreciate any suggestions.
HTML5 code: (For this example only I used the same audio source as a previous post: http://jsfiddle.net/RE006/8djstmvy/
<div>
<h2>Example 1</h2>
<audio id="sound1" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls="controls" preload="none">
<p>Your browser does not support the audio element.</p>
</audio>
</div>
<div>
<h2>Example 2</h2>
<audio id="sound2" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls="controls" preload="none">
<p>Your browser does not support the audio element.</p>
</audio>
</div>
JavaScript:
var $ = function (id) {
return document.getElementById(id);
}
var sound1_click = function() {
//starts playing
$("sound1").play ();
//pause playing
$("sound2").pause();
}
var sound2_click = function() {
//starts playing
$("sound2").play ();
//pause playing
$("sound1").pause();
}
window.onload = function () {
$("sound1").onclick = sound1_click;
$("sound2").onclick = sound2_click;
}