Next I introduce several ways of playing audio in Android, Android.media package below contains the Android development media class, of course, I will not go to the introduction, the following describes a few audio playback commonly used classes:
1. Play Audio using MediaPlayer
The MediaPlayer feature is very powerful, with a life cycle diagram of this class of packaged audio:
MediaPlayer support AAC, AMR, FLAC, MP3, MIDI, OGG, PCM and other formats, MediaPlayer can set the metadata and playback source to audio.
1.1 Play metadata for audio below the raw folder
// directly created, no setup required Setdatasource MediaPlayer Mmediaplayer;
Mmediaplayer=mediaplayer.create ( this
Mmediaplayer.start ();
1.2 Play an audio file by setting the playback source Setdatasource (String path)
// load Music from SD card mmediaplayer.setdatasource (".. /music/samsara.mp3 "); // load Music mmediaplayer.setdatasource from the network ("Http://..../xxx.mp3"); // use asynchronous Buffer Mmediaplayer.prepareasync ();
Setdatasource (FileDescriptor FD)
// The resource file needs to be placed in the assets folder Assetfiledescriptor fd = Getassets (). OPENFD ("Samsara.mp3"
Setdatasource (Context Context,uri Uri)
This method has nothing to say, generally get the URI from the shared music provided by the Android system via ContentProvider, and then set the data to play
Setdatasource (filedescptor fd,long offset,long length)
// The resource file needs to be placed in the assets folder Assetfiledescriptor fd = Getassets (). OPENFD ("Samsara.mp3"); Mmediaplayer.setdatasource (FD, Fd.getstartoffset (), Fd.getlegth ()) Mmediaplayer.prepare ();
After setting up the data source, do not forget prepare (), use asynchronous Prepareaync () as much as possible, and do not block the UI thread.
1.3 Common methods
Start (); // Start play pause (); // pauses playback of Reset ()// clears data setlooping (boolean) in MediaPlayer; // sets whether to loop Seekto (msec)// position to audio data, unit milliseconds stop (); // Stop playing relase (); // Freeing Resources
2. Play audio using Soundpool
3. Play audio using Androidtrack
4. Play Audio using Asyncplayer
5. Play Audio using Jetplayer
6. Play Audio using ringtone
7. Summary
Several ways to play audio from "Android"