Tuesday, August 16, 2011

Auto-playing Sound on the iPad and iPhone

I'm working on a project that involves JavaScript polling a server to check for new messages. One feature request was to have an audible alert if a new message comes in. Easy enough with HTML5 hottness:

// Declare the sound resource
var alert_sound = new Audio('path/to/alert.mp3');

// Play the sound on int he polling function
function message_load() {
    if(new_message) {
        alert_sound.play();
    }
    // Whatever else needs to be done
}

Great! We're done. Except that doesn't work on iOS because:
Warning: To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript. (from Apple)
Well great, but I don't think a 28.3k file is going to use that much data. In order for the sound to play with an asynchronous update, the user first needs to 'initiate' the sound:

// Continuing from the code above

// Assumes you have jQuery loaded

// Check to see if the device is an iPad
function is_ipad(){
    return (navigator.platform.indexOf("iPad") != -1);
}

// The function to bind to the link above
function alert_sound_load() {
    // Loads the sound
    alert_sound.load();
    // Plays the sound so the user can hear what it will sound like
    alert_sound.play();
    // Changes the text to show the user the sound alert is enabled
    $(this).text('Sound Alert Enabled').css("font-size","80%");
}


$(document).ready(function(){
    if(is_ipad()) {
        // If its an iPad, ask the user if they want to enable the new message alert
        $('#alert_sound_container').html('Click to Enable the New Message Alert');

        $('#alert_sound_load').click(alert_sound_load);
    }
});

When the user clicks to enable the sound alert, they will hear the sound play once. Anytime the .play() method is called, even on an asynchronous update, it will play since the user initiated it.

Of course this is only good for the current session. If the page is closed or refreshed, the user will have to click to enable the sound alert again, but it has been working well thus far.

I welcome your feedback, comments and suggestions below.

0 comments:

Post a Comment