nstudio / nativescript-audio

:microphone: NativeScript plugin to record and play audio :musical_note:
Other
149 stars 104 forks source link

Fix android audio focus management #165

Closed danieldspx closed 3 years ago

danieldspx commented 3 years ago

Everytime we instantiate TNSPlayer() it was requesting the audio focus and not abandoning it (until we call dispose() which is not always what we want). This is not recommended according to Android documentation and introduces a bug since this is not the expected behaviour. Those issues are facing exactly this bug: #142 #137

Android docs states that a well-behaved audio app should manage audio focus according to these general guidelines:

Call requestAudioFocus() immediately before starting to play and verify that the call returns AUDIOFOCUS_REQUEST_GRANTED. If you design your app as we describe in this guide, the call to requestAudioFocus() should be made in the onPlay() callback of your media session.

When another app gains audio focus, stop or pause playing, or duck the volume down.

When playback stops, abandon audio focus.

Therefore this pull request strictly obeys Android docs and fix the problem. It does not break existing code, only introduces the expected behaviour. So anyone can update the package and get the expected behaviour. I have also introduced the possibility to pass the durationHint (default is still AUDIOFOCUS_GAIN) to TNSPlayer constructor so we can determine differents behaviors by the system and the other application that previously held audio focus. Refer to the updated README.md .

bradmartin commented 3 years ago

Incredible PR work @danieldspx - thanks I'll have this merged and pushed shortly.