Playing sound from INACTIVE browser tab

后端 未结 2 1604
情歌与酒
情歌与酒 2021-01-01 18:40

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

相关标签:
2条回答
  • 2021-01-01 19:28

    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

    0 讨论(0)
  • 2021-01-01 19:34

    There's also the possibility that the audio wouldn't play because of browsers Autoplay policy.

    For example, in Chrome the audio won't play until the user actively click the web page.

    you may find the full list here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

    0 讨论(0)
提交回复
热议问题