Android Audio Playback Programming How-To

Tagged as: android mobile

Android Audio programming for an app developer consists of two main areas - Audio Capture and Audio Playback.

We will now discuss about Audio Playback. There are many intricacies to be handled, not a lot of code but the correct programming is important to build a stable app.

  1. Decide and configure which Audio Stream your app wants to use. The streams are Music, Ringtone, Voice, Alarm call etc. A music player will use Music stream. This for example ensures that when user uses the volume button, it changes the Music volume and not phone's ring tone. Use setVolumeControlStream(AudioManager.STREAM_MUSIC);

  2. Listen to hardware buttons, bluetooth headset playback buttons etc (not just soft buttons in your app). Unless you do this, app cant be controlled from say, your car's bluetooth

    1. Write a receiver for this event: android.intent.action.MEDIA_BUTTON. Register it in Manifest
    2. Use AudioManager.registerMediaButtonEventReceiver() to start listening, and also promptly unregisterMediaButtonEventReceiver when you are done. Typically you do this when you have audio focus (more on this below).
    3. Special Note: Handle this KEYCODE_HEADSETHOOK if you need to respond to wired headset plug-in events, and audio should route to it automatically.
  3. Audio Focus: Which app gets to play audio at any given point is decided by who has Audio Focus.

    1. When you need to play audio, call AudioManager.requestAudioFocus(). If this is successful you can start playback. At the point you can also possibly register for the above buttons events as well. You get the results via OnAudioFocusChangeListener()
    2. Use AudioManager.abandonAudioFocus() when you are done, so that other apps can use (very important !)
    3. While your app has focus, it is possible that another app requests focus and you lose it. Listen for this and you can possibly pause/stop the playback. In certain cases, your focus loss is transient (will get back automatically soon). Here you may duck - A classic case is when an SMS tone is played while you are playing music. This is transient, so you may just decide to lower your volume (and not pause).
  4. Adjust output for different hardware: You can use these methods to adjust output (say volume level), depending on whether playback is happening from headset, speaker etc: isBluetoothA2dpOn(), isSpeakerphoneOn(), isWiredHeadsetOn()

  5. Respond to hardware changes (say bluetooth off): When an AUX cable is plugged out or Bluetooth is OFF, a well behaved app should possibly pause the audio rather than suddenly shouting loud on speaker. So listen to ACTIONAUDIOBECOMING_NOISY and act appropriately

  6. Background Audio: Your app might be playing audio even when user is not interacting with the app or even when the display is off. Consider and use these methods to tune the behavior in such scenarios. Use them judiciously since there is power impact: setWakeMode() and setScreenOnWhilePlaying().WifiLock is another one to consider if you are streaming.

  7. Ensure that your app is trying to play only supported media formats. Generally mp3 and m4a works well. Detailed list in the references below.

  8. Use Asynchronous calls, like MediaPlayer.prepareAsync() instead of prepare(), so that application is responsive. Also remember to release it when you are done to prevent any memory leaks - use release()

  9. Handle Errors: Even if you try your best, some audio might fail on playback. So remember to handle errors using AudioManager.OnErrorListener, and handle it well (say, tell user the next steps if it fails)

  10. Android Media Player internal States are documented well. Consider understanding it (see references below)

  11. Foreground Service: You typically need audio to be playing even when the app is not in focus (usually in a small player in notification area). For this, do the MediaPlayer in a Foreground service. Use Service.startForeground(), so that you don't get killed by system often. Remember to call stopForeground() as well, when your playback is done.

Most of these insights have been from the experience of rolling out our Audio Apps. Take a look if you like:

  1. AiringPods for Podcasts
  2. SaptaSwara for Indian Classical Music

References: Managing Android Audio, Android Supported Audio Formats, Media Player States

Tagged as: android mobile
comments powered by Disqus