hoanganh17b
hoanganh17b

Reputation: 867

Play audio in inactive tab with JavaScript

I write a web chat using Websocket. Problem is user switch browser's tabs and I want to play a sound to let them know that someone want to talk to him in chat's tab.

I saw FaceBook and GMail can play a 'ping' once their chat have new message in inactive tab.

How do they do it with JavaScript or there are any solutions?

Upvotes: 4

Views: 2107

Answers (1)

clayperez
clayperez

Reputation: 845

How's this?

function beep(file,volume){
    var snd = new Audio(file);
    volume = volume ? volume : 0.5; // defaults to 50% volume level
    snd.volume = volume;

    // LISTENER: Rewind the playhead when play has ended
    snd.addEventListener('ended',function(){
        this.pause();
        this.currentTime=0;
    });

    // Play the sound
    snd.play();
}

beep("audioFiles/beep.mp3", 1.0);

Upvotes: 5

Related Questions