3

I am using an audio-player package to play a sound locally when a node app triggers an event. When the event is triggered, a function is called with the specific file that needs to be opened as such:

playSound(fileName);

The separate function looks like this:

player = new Player('someDirectory/' + fileName + '.mp3');
player.play();

This opens and begins playing the file perfectly well, however when events trigger in quick succession, both sounds will be simultaneously playing. While I initially thought to simply add a:

player.stop();

before the 'new Player' definition, the previous instance is clearly out of scope, as the function has been called a second time. How can I stop all other instances of Player before starting playback anew?

2 Answers 2

1

You need to declare the player variable in the outer scope, so that every function "sees" the same player.

var player;

function playSound(fileName) {
    if (player) {
        player.stop();
    }

    player = new Player(fileName);
    player.play();
}

This is called a closure.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, wonderful. I should have known to reassign player with every call. Thanks for the spot-on answer!
0

Your player should be static, only one instance should exist and play all sounds.

function Podcast() {};

Podcast.FILE_EXTENSION = 'mp3';
Podcast.download = function(podcast) {
    console.log('Downloading ' + podcast + ' ...');
};

Here we created a constructor function named Podcast with a static property called FILE_EXTENSION and a static method named download.

http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.