I have 2 audio tags and a button
When I click the button, if it's true I want to play sound1 and if it's not I want to play sound2
<button>play</button>
<audio class="sound1" src="sound1.mp3" ></audio>
<audio class="sound2" src="sound2.mp3" ></audio>
jQuery:
$('button').click(function() {
if (true) {
audio.play();
} else {
}
});
I don't know how to get the audio object by a class name
I have 2 audio tags and a button
When I click the button, if it's true I want to play sound1 and if it's not I want to play sound2
<button>play</button>
<audio class="sound1" src="sound1.mp3" ></audio>
<audio class="sound2" src="sound2.mp3" ></audio>
jQuery:
$('button').click(function() {
if (true) {
audio.play();
} else {
}
});
I don't know how to get the audio object by a class name
Share Improve this question edited Feb 20, 2017 at 17:58 Mr. Alien 157k36 gold badges303 silver badges285 bronze badges asked Feb 20, 2017 at 17:47 Andre SilvaAndre Silva 332 silver badges5 bronze badges 1-
document.getElementsByClassName("sound1")[0];
– Sourav Ghosh Commented Feb 20, 2017 at 17:53
2 Answers
Reset to default 4You need to use .play()
to trigger the audio, and use $(selector).get(0)
to get the audio object.
$('button').click(function(){
if ( true ) {
$('.sound1').get(0).play();
} else {
$('.sound2').get(0).play();
}
});
Demo (Toggle true / false
to hear .wav
and .mp3
file)
Audio Credits
the better way is to set the src of your audio according to your condition something like
$('button').click(function(){
// Select the sourceUrl according to your selection then set the source to your audio control
$('.sound').attr('src', sourceUrl);
}