Sound Play / Stop / Pause

I am developing a JavaScript sound library. I can play the sound with the code below.

var soundPlayer = null;

function playSound(){

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

}

How can I stop and pause this sound? 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 this?

+4
source share
1 answer

If you change this:

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

To that:

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

Your pause will work. The problem is that you have assigned a playback function to soundPlayer. SoundPlayer is no longer an Audio object.

Instead of stop () use:

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

It works the way I expect.

+5
source

Source: https://habr.com/ru/post/1673806/


All Articles