Gain audio focus in your app

By Published On: March 31, 2023Categories: Development

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

Leave A Comment

Latest Articles