Adding audio to your applications can take on many forms. This could be a sound-effect for a game, audio that is played on demand, or in the form of a podcast or audiobook.
The Android multimedia framework includes support for playing variety of common media types, so that you can easily integrate audio, video and images into your applications. You can play audio or video from media files stored in your application’s resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection.
Setting Your App Up for Audio
Before starting development on your application using MediaPlayer, make sure your manifest has the appropriate declarations to allow use of related features.
Internet Permission – If you are using MediaPlayer to stream network-based content, your application must request network access.
Wake Lock Permission – If your player application needs to keep the screen from dimming or the processor from sleeping, or uses the MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode()methods, you must request this permission.
One of the most important components of the media framework is the MediaPlayer class. An object of this class can fetch, decode, and play both audio and video with minimal setup. It supports several different media sources such as:
- Local resources
- Internal URIs, such as one you might obtain from a Content Resolver
- External URLs (streaming)
Playing Audio with MediaPlayer – Using the built-in MediaPlayer class to play audio, including local audio files and streamed audio files with the AudioTrackclass.
Recording Audio – Using the built-in MediaRecorder class to record audio.
Working with Audio Notifications – Using audio notifications to create well-behaved applications that respond correctly to events (such as incoming phone calls) by suspending or canceling their audio outputs.
Working with Low-Level Audio – Playing audio using the AudioTrack class by writing directly to memory buffers. Recording audio using the AudioRecord class and reading directly from memory buffers.
In addition to stopping the MediaPlayer you want to call the release() method on the object when you are done with the audio to free up resources.