Joshua Thomas
Joshua Thomas

Reputation: 21

Starting/Stopping sound with javascript onClick

this is my first post and I have searched a bit for an answer, but haven't come across any solutions.

Basically all I want to do is make onClick="" both start and stop audio with the javascript function, playSound(sound). Here is what I've ended with so far. Right now, no audio plays when I click, but when I test the single code 'song1.play()' by itself the sound plays, but obviously doesn't stop when clicked again. Hopefully this isn't too difficult.

function playSound(sound){
        var song1=document.getElementById(sound);
        var isPlaying = true;
        if (!isPlaying){
            isPlaying == true;
            song1.play();
        } 
        else{
            isPlaying == false;
            song1.pause();
        }
    }

Upvotes: 2

Views: 1869

Answers (4)

Djaouad
Djaouad

Reputation: 22766

You can check if a sound is paused using the paused property:

function playSound(sound) {
  var song1 = document.getElementById(sound);
  song1.volume = .25; // setting the volume to 25% because the sound is loud
  if (song1.paused) {  // if song1 is paused
    song1.play();
  } else {
    song1.pause();
  }
}
<audio id="sound">
  <source src="https://www.w3schools.com/TagS/horse.mp3" type="audio/mp3">
</audio>
<button onclick="playSound('sound')">Play/Pause</button>

Upvotes: 1

MKR
MKR

Reputation: 20085

Two small corrections.

a) var isPlaying = true; should be declared globally to retain its values between multiple calls to "OnClick".

b) The == should be changed to = in assignment statements of `isPlaying' variable.

var isPlaying = true;
 function playSound(sound){
            var song1=document.getElementById(sound);
            if (!isPlaying){
                isPlaying = true;
                song1.play();
            } 
            else{
                isPlaying = false;
                song1.pause();
            }
        }

Upvotes: 2

Satish Kumar
Satish Kumar

Reputation: 601

You should use = instead of ==

= is Assignment operator where as == is comparison operator.

Upvotes: 0

Ecstabis
Ecstabis

Reputation: 444

You were comparing the isPlaying variable with true and false, instead of assigning them to the variable. This should work now.

function playSound(sound){
    var song1=document.getElementById(sound);
    var isPlaying = true;
    if (!isPlaying){
        isPlaying = true;
        song1.play();
    } 
    else{
        isPlaying = false;
        song1.pause();
    }
}

Upvotes: 0

Related Questions