Why u do dis
Why u do dis

Reputation: 458

How to pause Audio when the same Audio is playing in Javascript

I have this code

const gameSounds = {
  backgroundTheme: function(){
    const backgroundTheme = new Audio('./gameSounds/theme.mp3');

    if(backgroundTheme){
      backgroundTheme.pause();
    }
      backgroundTheme.play();
    
  }

I have a start button that I have added an event listener of click and when the click happens then the audio will begin playing but at the moment you can click the start button multiple times and the audio will play several times at the same time which is not something I want to happen.

I thought of writing an if statement that would check if the audio is already playing then pause it or restart it but I am not sure what to write inside the if() I tried if(backgroundTheme.play()) but that didn't work... Any ideas ?

Upvotes: 1

Views: 133

Answers (1)

Justinas
Justinas

Reputation: 43479

First of all - you must create new Audio only once and act on it later on.

Have global variable that holds state of your player:

var audioObject;
var isPlaying = false;

const gameSounds = {
  backgroundTheme: function(){
    if (typeof audioObject === 'undefined') {
        audioObject = new Audio('./gameSounds/theme.mp3');
    }

    if(isPlaying){
      backgroundTheme.pause();
    } else {
      backgroundTheme.play();
    }

    isPlaying = !isPlaying;
  }

Upvotes: 2

Related Questions