使用 JavaScript 在非活动选项卡中播放音频

hoa*_*17b 4 javascript dom-events

我使用 Websocket 编写网络聊天。问题是用户切换浏览器的选项卡,我想播放声音让他们知道有人想在聊天选项卡中与他交谈。

我看到 Facebook 和 GMail 可以在非活动选项卡中的聊天中有新消息时播放“ping”。

他们是如何用 JavaScript 做到这一点的,或者有什么解决方案吗?

cla*_*rez 5

这个怎么样?

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);
Run Code Online (Sandbox Code Playgroud)