Outside scope objects in NodeJS

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

playSound(fileName);

      

A separate function looks like this:

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

      

This opens and starts playing the file fine, however, when events are triggered quickly, both sounds will play at the same time. Although I originally thought to just add a:

player.stop();

      

before the definition of "new player", the previous instance is clearly out of scope since the function was called a second time. How can I stop all other instances of the Player before starting over again?

+3


source to share


2 answers


You need to declare the variable player

in the outer scope so that each function "sees" the same player.

var player;

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

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

      



This is called snapping.

+1


source


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

function Podcast() {};

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

      



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

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

0


source







All Articles