PhoneGap Plays Sounds on Mute

The Cordova / PhoneGap media plugin

As part of my recent game development, there’s a requirement to play short audio sound effects, based on user interaction. There are several options available for doing this but I opted for using a native component using the core Apache Media Plugin.

Working in 60 seconds, but…

It worked like a treat within seconds of wiring it up, but to my horror, the sound samples were still played when the device (iPhone) was muted by the physical mute button!

What the!? Not great if you want to play my game on a train.

Muted Audio

Why Why Why

There are various policies that dictate whether or not a sound is played, interrupted or muted. Cordova / PhoneGap creates an audio session, that was originally designed for apps like Spotify and YouTube that want to play media regardless of the phone state and even if the app isn’t open (screen is locked).

The solution

My initial instinct was to query the state of the mute switch, but I really didn’t want to write a plugin just to do that - I might as well switch to another option for playing the sounds in the actual web view.

After delving into the plugin source I found an option, an option (that is not the default) to make the audio session obey the mute switch. playAudioWhenScreenIsLocked. Yes that’s right, setting playAudioWhenScreenIsLocked will force the plugin to react to the state of the hardware mute button.

Full example

Here’s the code you need to play audio that obeys the mute switch:

Install the media plugin

$ cordova plugin add

In your JavaScript

var playAudio = function (file) {
var media = new Media(file);{ playAudioWhenScreenIsLocked : false });

An incontinent mute, goes without saying.