Search code examples
javascripthtmlnotificationshowler.js

Can audio be triggered to play during phone lock


I am making a web chat app and now I am in need of playing notification sounds as a new message arrives.

To begin with I am using howler.js to play the sounds. In howler we can start playing a sound and then if we lock the screen or change browser tab focus it keeps playing. But it doesn't start playing the sound if the tab is opened and mobile screen is locked nor does it play if the user is on another tab with the app on another tab opened.

So basically my question is, is it possible to start playing sound even when screen is locked or start playing the sound when user is on another tab?

app.js

var notify_sound = new Howl({
    src: ['./assets/sounds/notify2.mp3'],
    volume: 1.0
});
.
.
.
.
.
.
.
.
if(type == "user"){
        if(userAddress == remoteAddress) {
            typing.html('').fadeOut('fast');
            messages.append('<li class="self"><p class="message">'+ obj.message + '</p><p class="time">' + time +'</p></li><p class="username_self">' + userAddress + '</p>');
        }
        else {
            typing.html('').fadeOut('fast');
            messages.append('<li class="other"><p class="message">'+ obj.message + '</p><p class="time">' + time +'</p></li><p class="username_other">' + userAddress + '</p>');

            notify_sound.play();
        }
    }

Solution

  • HTML5 audio and mobile don't really get along. Howler.js (If you're using 2.0) uses a workaround to get audio to 'autoplay' at all by attaching an event handler to the first touch event that'll trigger playback. If the view isn't active, there won't be a touch event (even a simulated one) to trigger playback.

    From the docs:

    Mobile Playback

    By default, audio on iOS, Android, etc is locked until a sound is played within a user interaction, and then it plays normally the rest of the page session (Apple documentation). The default behavior of howler.js is to attempt to silently unlock audio playback by playing an empty buffer on the first touchend event. This behavior can be disabled by calling:

    Howler.mobileAutoEnable = false;

    If there's no initial interaction, there's not much you can do.