Search code examples
androidaudiocordova-plugins

android cordova-media-plugin don't demand audio focus


I am making a dirt simple app for myself because I would like to play the sound of rain at the same time as listening to an audiobook in another app.

As I understand it, there's something in java land that does a requestAudioFocus. Snippet from cordova-plugin-media:

AudioManager am = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
        int result = am.requestAudioFocus(focusChangeListener,
                                          AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);

Years ago, I could make most apps play audio at the same time. I thought maybe this has just become 'best practice' to not play audio at the same time (battery life reasons, or something like that), but if it's just an app for me, that's not a concern.

I thought I could solve this just by taking this plugin and not demanding audio focus, but it looks like that's implicit. Is there a way to say not to? So if I start playing an audio book in another app, my app won't pause it when it starts playing rain sounds?

Can it be done from Javascript, can I edit the java plugin? (Not a java programmer). Or is this perhaps just imposed by the current android OS?

Here is my code, though it does nothing interesting:

var path = '/android_asset/www/rain.mp3';

var media = new Media( path,
                       ()  => alert('success'),
                       err => document.body.innerHTML = JSON.stringify(err) );
media.play({ numberOfLoops: 10, playAudioWhenScreenIsLocked : true });

Thanks in advance,


Solution

  • The Cordova plugin you mention indeed requests audio focus when it starts playing the stream: see startPlayingAudio() [Github link] and Android AudioFocusRequest documentation

    This means that when you start your app, it will automatically ask the audiobook app to pause.

    It would be helpful if it would be possible to also request for instance AUDIOFOCUS_GAIN_TRANSIENT if you want your app to only provide small sound effects or spoken hints, and have that not stop an app as Spotify playing in the background; this plugin does not provide such functionality.

    You could modify this plugin so you can make getting audio focus optional, or TRANSIENT; or you could decide to write your 'dirt simple' app in native Android so you have more direct control over the APIs.