Handling audio focus while writing media player apps for android
In this post, I am not going to tell you how to write media player app for Android. You will find several blog posts on that. In this post, I am going to write how you can handle the audio focus. Before we start, I am going to list a few links on creating a media player for android for you.
These are just a few examples.
OK, let's get back to the original topic. If you have multiple apps that play audio then you are going to hear all of them playing at the same time. In this tutorial we are going to stop any other audio from playing while our app plays the audio. Once the audio is played, we will let other apps continue playing their audio. The code below is an example implementation of audio focus.
For more information please visit: http://developer.android.com/training/managing-audio/audio-focus.html
How to create a media player app in android
- http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/
- http://code.tutsplus.com/tutorials/create-a-music-player-on-android-song-playback--mobile-22778
- http://www.tutorialspoint.com/android/android_mediaplayer.htm
These are just a few examples.
OK, let's get back to the original topic. If you have multiple apps that play audio then you are going to hear all of them playing at the same time. In this tutorial we are going to stop any other audio from playing while our app plays the audio. Once the audio is played, we will let other apps continue playing their audio. The code below is an example implementation of audio focus.
public AudioManager audioManager = null; protected void onCreate(Bundle savedInstanceState) { audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (requestAudioFocus()) { //focus gained start the player } else { //focus could not be gained Log.d(TAG, "AUDIO FOCUS REQUEST COULD NOT BE GRANTED"); } } private boolean requestAudioFocus() { int result = audioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { Log.d(TAG, "onAudio focus gained"); } }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); // transiet is for temporary only if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { return false; } Log.i(TAG, "focus gained"); return true; } private void abandonAudioFocus() { audioManager.abandonAudioFocus(new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { Log.d(TAG, "onAudio focus abandoned"); } }); }
For more information please visit: http://developer.android.com/training/managing-audio/audio-focus.html
Comments
Post a Comment