12

I'm developing a sound JavaScript library. I can play sound with below code.

var soundPlayer = null;

function playSound(){

soundPlayer = new Audio(soundName).play();

}

How can I stop and pause this audio? When I try like this:

soundPlayer.pause();

Or

soundPlayer.stop();

But I get this error:

Uncaught TypeError: soundPlayer.stop is not a function

How can I do that?

double-beep
  • 5,031
  • 17
  • 33
  • 41
jsawyer
  • 123
  • 1
  • 1
  • 5

1 Answers1

19

If you change that:

soundPlayer = new Audio(soundName).play();

To that:

soundPlayer = new Audio(soundName);
soundPlayer.play();

Your pause will be working. The problem is that you assigned "play" function to soundPlayer. SoundPlayer isnt an Audio object now.

Instead of stop() use:

soundPlayer.pause();
soundPlayer.currentTime = 0;

It works the same I guess.

5ka
  • 246
  • 2
  • 6
  • 1
    Yes. these two functions will be working if you change what I mentioned. Your soundPlayer is a function "play" now, not an Audio object. That is why stop and pause dont work. – 5ka Apr 02 '17 at 12:04
  • 1
    I changed my code with your code. Now, .pause() function is working. Thanks! But stop() function isn't working. How i do that? – jsawyer Apr 02 '17 at 12:08
  • 3
    Try soundPlayer.pause(); soundPlayer.currentTime = 0; – 5ka Apr 02 '17 at 12:10
  • There is no function like stop()? ``soundPlayer.currentTime = 0`` works though. – Toto Briac Apr 14 '22 at 06:17