Toggle play button and pause current audio instance when another is played

I have used this code as a template on the site I’m working on so thank you for that! I need the first audio to pause when another one is clicked and I have succeeded, however, the pause button remains on the first audio that gets paused, and I need it to toggle back to the play button image without actually being clicked, when the pause all audio except current is called…any help is appreciated.

Here is a pen: https://codepen.io/cindymariesilva/pen/aKdVXe

HTML:

<audio id="sound2"> <source src="/faq/audio/ogg/101_Narcissist_Monet.ogg" type="audio/ogg"> <source src="/faq/audio/mp3/101_Narcissist_Monet.mp3" type="audio/mpeg"> </audio>

<div class="play" id="2"></div>

Scripts (in external .js file):

$('.play').click(function(){ var $this = $(this);

// starting audio
var audioID = "sound" + $(this).attr('id');

$this.toggleClass('active');
if($this.hasClass('active')){
    $this.addClass('pause'); 
    $("#" + audioID).trigger('play');
} else {
    $this.removeClass('pause');
    $this.addClass('play');
    $("#" + audioID).trigger('pause');
}
});

Script in HTML file:

<script> window.addEventListener("play", function(evt) { if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target) { window.$_currentlyPlaying.pause(); } window.$_currentlyPlaying = evt.target; }, true); </script>

CSS: .play{ background-image:url('/faq/img/icon_play.svg'); background-size:contain; display:block; background-repeat: no-repeat; width: 3em; height: 3em; }

.pause{ background-image:url('/faq/img/icon_pause.svg'); background-size:contain; display:block; width:3em; height:3em; }

Well there’s a CSS solution to this.
define a CSS class for ‘play’, and one for ‘pause’, that defines the button image. The browser will take care of the rest.
(though i’m confused, because you seem to have 3 classes, active, play, and pause?)

1 Like

I do have the play / pause buttons toggling correctly. It is a CSS solution you are correct. The “active” class is telling when to toggle, when it is “active” or clicked.

If you look at the working codepen you will see them toggle…the problem is that I need all audio files to stop when another is clicked and this doesn’t toggle the image again because there is no “click” on the previous button to register…so I basically need to say - toggle image back when not playing I think.

So the toggle works…just need a way to tell it to toggle again whenever the audio is not playing after the JS function stops them. I hope this makes sense and thank you for your help.

So do exactly what you said. Stop ALL the audio files, and resume only the one that was clicked. There’s nothing to stop you from pausing something that’s already paused, and if you pause ALL of the audio files, it doesn’t matter which one(s) was/were clicked previously.

$(".audiofile").trigger('pause'); //Pause all audio files.
$("#"+audioID).trigger("play"); //Play selected audio file.
$(".pause").addClass("play"); //Set all Pause classed objects to Play.
$(".pause").removeClass("pause"); //Remove the pause class from any such objects.
$(this).addClass("pause"); //Add the pause class to the selected object.
$(this).removeClass("play"); //Remove the play class from the selected object;

EDIT: Forgot the last line.

1 Like

Hi there cindymariesilva,

does this example help…

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
    background-color: #000;
    font: 100% / 162% verdana, arial, helvetica, sans-serif;

 }
 
audio {
    position: absolute;
    left: -999em;
 }
 
#n1, #n2 {
    display: block;
    width: 3em;
    height: 3em;
    margin: 1em 0;
    background-size: contain;
    background-repeat: no-repeat;
 }
 
.play {
    background-image:url('http://motherdev.rankubator.com/faq/img/icon_play.svg');
 }
 
.pause {
    background-image:url('http://motherdev.rankubator.com/faq/img/icon_pause.svg');
 }
</style>

</head>
<body> 

 <audio id="sound1" controls>
  <source src="http://motherdev.rankubator.com/faq/audio/mp3/101_Narcissist_Peter.mp3">
  <source src="http://motherdev.rankubator.com/faq/audio/ogg/101_Narcissist_Peter.ogg">
 </audio>

 <span class="play" id="n1"></span>

<!-- Sound 2 -->
 <audio id="sound2" controls>
  <source src="http://motherdev.rankubator.com/faq/audio/ogg/101_Narcissist_Monet.ogg" type="audio/ogg">
  <source src="http://motherdev.rankubator.com/faq/audio/mp3/101_Narcissist_Monet.mp3" type="audio/mpeg">
 </audio>

 <span class="play" id="n2"></span>

<script>
(function( d ) {
   'use strict';
  var n1 = d.getElementById( 'n1' ), n2 = d.getElementById( 'n2' ),
      s1 = d.getElementById( 'sound1' ),s2 = d.getElementById( 'sound2' );
	  
      n1.addEventListener( 'click', function() {
         if ( this.className === 'play' ){
              this.classList.remove( 'play' );
			  this.classList.add( 'pause' );
			  n2.classList.remove( 'pause' );
			  n2.classList.add( 'play' );
			  s2.pause();
			  s1.play();
           }
         else {
              this.classList.remove( 'pause' );
			  this.classList.add( 'play' );
			  s1.pause();
		   }
		  }, false );
		  
      n2.addEventListener( 'click', function() {
         if ( this.className === 'play' ){
              this.classList.remove( 'play' );
			  this.classList.add( 'pause' );
			  n1.classList.remove( 'pause' );
			  n1.classList.add( 'play' );
			  s1.pause();
			  s2.play();
           }
         else {
              this.classList.remove( 'pause' );
			  this.classList.add( 'play' );
			  s2.pause();
		   }
		  }, false );
		  
      s1.addEventListener( 'ended', function() {
                          this.load();
			  n1.classList.remove( 'pause' );
			  n1.classList.add( 'play' );
	    }, false );

      s2.addEventListener( 'ended', function() {
                          this.load();
			  n2.classList.remove( 'pause' );
			  n2.classList.add( 'play' );
	    }, false );	  
}( document ));
</script>

</body>
</html>

coothead

Yes! Thank you for your help - this is SOOO close to the desired effect.

However, now you cannot pause/stop the audio on clicking the buttons - the audio continues to play unless you click another audio or close the window. The user needs to be able to pause a file on click not just pause when another file is clicked.

Here is the solution and working codepen in case anyone else has the same issue.

// jQuery
$('.play').click(function(){
    var $this = $(this);
    
    // starting audio
    var audioID = "sound" + $(this).attr('id');
    
    $this.toggleClass('active');
    if($this.hasClass("active")){
    $(".pause").removeClass("pause");
    $(".active").removeClass("active");  
    $(this).addClass("active pause");  
    $("#" + audioID).trigger("play");  
    } else {
        $this.removeClass('pause');
        $this.addClass('play');
        $("#" + audioID).trigger('pause');
    }
});
1 Like

Good to see you got it working :slight_smile:

My version isn’t much different:
https://codepen.io/EtoileLion/pen/vrGLKg

1 Like

Thank you! I couldn’t have done it without you!

While we are at it…any suggestion to add a stop button separate from these audio instances?

here is the website:

http://motherdev.rankubator.com/faq.php

When you click one of the posters, content is revealed that shows these audio files, etc there is a “close” button on the top of each entry and there are 66 total responses. There will also be an inner page and a secondary button.

I need to stop playing all audio on click of the close button.

I’m also adding a rewind button.

Looking at your HTML, the audio elements are still present in the DOM even when they’re not visible on screen. Therefore your jQuery can and will still interact with them.

Somewhere, you’ve bound an event to the close buttons to hide/show the FAQ sections. Add code to that to:
Trigger a Stop (or pause?) in all audio elements.
Add the Play class to anything with the Pause class
Remove the Pause class from all elements with the Pause class.
(Hint: All three of those things we’ve already done…)

Apoligises if I am asking incorrectly posting or asking incorrectly within the site as I am a “Newbie”. I came across this while searching for a method to play audio on a webpage and was wondering if it ok to use with prmission, I would also like to ask if possible how to use the rewind feature you have implented along with the play/pause. Can a example be shown? may permission be given to use? Great site by the way and TIA for any reply.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.