Emese Pócsik Emese Pócsik - 5 months ago 26
Javascript Question

jQuery: Multiple audio player buttons

I would like to make 4 play buttons which plays mp3 audio. The play function is working every 4 buttons, but unfortunately the pause is not working for either of them. Maybe the pause condition is wrong?

<div class="audio-button">
<audio src="media/test.mp3"></audio>
</div>
<div class="audio-button">
<audio src="media/test2.mp3"></audio>
</div>
<div class="audio-button">
<audio src="media/test3.mp3"></audio>
</div>
<div class="audio-button">
<audio src="media/test4.mp3"></audio>
</div>


$(document).ready(function() {
var playing = false;

$('.audio-button').click(function() {
$(this).toggleClass("playing");
var song = $(this).find('audio').attr('src');
var audio = new Audio(song);

if (playing == false) {
audio.play();
playing = true;
} else {
audio.pause();
playing = false;
}
});
});

Answer

You need to grab the audio element directly from the button as a child and interact with that. You do not need to clone the Audio object using a constructor.

$(document).ready(function() {
  var playing = false;

  // Add file names.
  $('.audio-button').each(function() {
    var $button = $(this);    
    var $audio = $button.find('audio');
    
    $($('<span>').text($audio.attr('src'))).insertBefore($audio);
  });

  // Add click listener.
  $('.audio-button').click(function() {
    var $button = $(this);    
    var audio = $button.find('audio')[0]; // <-- Interact with this!
    
    // Toggle play/pause
    if (playing !== true) {
      audio.play();
    } else {
      audio.pause();
    }

    // Flip state
    $button.toggleClass('playing');
    playing = !playing
  });
});
.fa.audio-button {
  position:      relative;
  display:       block;
  width:         12em;
  height:        2.25em;
  margin-bottom: 0.125em;
  text-align:    left;
}

.fa.audio-button:after {
  position:      absolute;
  right:         0.8em;
  content:       "\f04b";
}

.fa.audio-button.playing:after {
  content:       "\f04c";
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="fa audio-button">
  <audio src="media/test.mp3"></audio>
</button>
<button class="fa audio-button">
  <audio src="media/test2.mp3"></audio>
</button>
<button class="fa audio-button">
  <audio src="media/test3.mp3"></audio>
</button>
<button class="fa audio-button">
  <audio src="media/test4.mp3"></audio>
</button>