Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

javascript - Playing sound from INACTIVE browser tab

I have a control panel for restaurants and it plays an alert sound when an order is given. The problem is that when the control panel tab is not the active tab in Chrome (it's also same for Firefox) the alert sound doesn't play. After clicking the tab it plays the sound.

I see some sites (Facebook Chat, Cloudstats.me server alert, ...) play sound even if they are in inactive tab, so what is the workaround for this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Had a similar thing happen to me as well, we were trying to play a marketclock when the stock market opened and closed for the day. The issue we had was we tried to load the mp3 then play it when the condition is met. So originally I had.

var bell;

// Update the clock, countdown, and tooltips as needed.
function updateClock() {
    service.getMarketDate(function(data) {

        if (data.soundMarketBell) {
            if (!bell) {
                bell = new Audio('/sounds/marketclock.mp3');
            }
            bell.play();
        }
    });
}

var intervalId = $interval(updateClock, 1000);

By moving the resource loading to happen on page load and then just calling the Audio.play it fixed the issue

var bell = new Audio('/sounds/marketclock.mp3');

// Update the clock, countdown, and tooltips as needed.
function updateClock() {
    service.getMarketDate(function(data) {
        if (data.soundMarketBell) {
            bell.play();
        }
    });
}

// check for a time update every second
// to balance accuracy with performance
var intervalId = $interval(updateClock, 1000)

Browsers restrict loading resources when a tab is inactive


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...