Gain audio focus in your app

Hey folks,
Back with a very interesting topic. If you are working with the OTT app or you are dealing with any app handling media stuff. You must’ve encountered this feature or asked by the product to snatch audio focus if an app is playing music in the background.
In this article, I’ll be explaining different types of audio focus requests and best practices to avoid any QA revision ;).
Before we jump into code or further technical details I’ll explain to you some approaches for Audio focus.
Request focus right before you want to use a specific media feature and release focus back
Request focus on app resume state to avoid any app gaining focus while your app is in the foreground
For the first approach mentioned in this article, you need to call focus gainer right before you want to play media. This is a kind of lazy approach and depends on business logic as well. If your app is not Media, OTT, Recorder, or only player based then go with this approach.
If your app is total media, ott, recording, or multimedia-based use case where you are playing media frequently from various points in your app, then you need to go with the second approach.
Enough discussion on use cases and approaches, let’s get some technical stuff on.
In the above Gist, I’ve used AndroidX libraries instead of old android audio libraries.
There are multiple types of Audio requests one can make and can vary on the basis of one’s use case.
For example, I’ve requested focus until my player is active so I requested a short time focus by using AUDIOFOCUS_GAIN_TRANSIENT.
There are a few other options for example AUDIOFOCUS_GAIN, AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE, and AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK.
Below Gist explains the use case of audio focus.
I hope it was worth it for the ones whom it may concern. Github project for this example is attached.
Happy Voding, Happy Coding 😉
Will see you in the next article, bye!!
Share this article

Written by : admin
Latest Articles
June 21, 2024
June 11, 2024
June 10, 2024
May 31, 2024
May 27, 2024
May 10, 2024
February 1, 2024
December 28, 2023
December 26, 2023
December 18, 2023
December 15, 2023
September 26, 2023
September 21, 2023
September 19, 2023
September 19, 2023
September 12, 2023
September 5, 2023
August 29, 2023
March 31, 2023
March 20, 2023
March 13, 2023
March 13, 2023
March 13, 2023
March 13, 2023
March 13, 2023