Introduction
Consider we are creating an audio player application. There may be a chance of creating noisy output on the speaker because another app uses the audio hardware at the same time. To reduce this, Android has a built-in API called AudioFocusRequest.
Step 1
We have to register for an audio listener, so that the listener class will provide the information whether another application is using the audio or not.
Step 2
Add the following code to the class where you're going to implement the listeners. We have to get the audio service using AudioManger.
- public bool RequestAudioFocus()
- {
- var amanager = (AudioManager)GetSystemService(AudioService);
- AudioFocusRequest audioFocusRequest;
- if (Build.VERSION.SdkInt > BuildVersionCodes.O)
- {
- audioFocusRequest = amanager.RequestAudioFocus(new AudioFocusRequestClass.Builder(AudioFocus.Gain)
- .SetAudioAttributes(new AudioAttributes.Builder().SetLegacyStreamType(Stream.Music).Build())
- .SetOnAudioFocusChangeListener(this)
- .Build());
- }
- else
- {
- audioFocusRequest = amanager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain);
- }
-
- if (audioFocusRequest == AudioFocusRequest.Granted)
- {
- return true;
- }
- return false;
- }
Step 3
Implement the interface "AudioManager.IOnAudioFocusChangeListener" which implements a method called.
OnAudioFocusChange.
- public void OnAudioFocusChange([GeneratedEnum] AudioFocus focusChange)
- {
- }
Step 4
Inside "OnAudioFocusChange" Method implement the switch case to handle the audio Focus.
- switch (focusChange)
- {
- case AudioFocus.Gain:
-
-
-
- }
- break;
- case AudioFocus.Loss:
-
-
- break;
- case AudioFocus.LossTransient:
-
-
- break;
- case AudioFocus.LossTransientCanDuck:
-
-
- break;
- }
Step 5
The final implemetation will be like below.
- public class AudioFocus : AudioManager.IOnAudioFocusChangeListener
- {
- public AudioFocus()
- {
- RequestAudioFocus();
- }
- public bool RequestAudioFocus()
- {
- audioManager = (AudioManager)GetSystemService(AudioService);
- AudioFocusRequest audioFocusRequest;
- if (Build.VERSION.SdkInt > BuildVersionCodes.O)
- {
- audioFocusRequest = audioManager.RequestAudioFocus(new AudioFocusRequestClass.Builder(AudioFocus.Gain)
- .SetAudioAttributes(new AudioAttributes.Builder().SetLegacyStreamType(Stream.Music).Build()) .SetOnAudioFocusChangeListener(this)
- .Build());
- }
- else
- {
- audioFocusRequest = audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain);
- }
-
- if (audioFocusRequest == AudioFocusRequest.Granted)
- {
- return true;
- }
- return false;
- }
-
- public void OnAudioFocusChange([GeneratedEnum] AudioFocus focusChange)
- {
- switch (focusChange)
- {
- case AudioFocus.Gain:
-
-
- break;
- case AudioFocus.Loss:
-
-
- break;
- case AudioFocus.LossTransient:
-
-
- break;
- case AudioFocus.LossTransientCanDuck:
-
-
- break;
- }
- }
- }
At last, remember to release the audio service.