Andre Silva
Andre Silva

Reputation: 33

jQuery play audio by selector

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

Upvotes: 3

Views: 7858

Answers (2)

Frenchi In LA
Frenchi In LA

Reputation: 3169

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);
}

Upvotes: 0

Mr. Alien
Mr. Alien

Reputation: 157324

You 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

Upvotes: 4

Related Questions