There are generally 3 ways to play audio on the Android platform. 1. Play audio using the system's built-in application 2. Play the original audio with Audiotrack 3. Play with MediaPlayer. This 3 kinds of audio playback mode, the third kind of mediaplayer play this way to use the most, must master!
First, use the system built-in programs.
Google think "thoughtful", generally give us some built-in programs, but these built-in program UI effect, that is really touching ah! Generally built-in programs, we just look at it.
Intent intent=new Intent (Intent.action_view); Intent.setdataandtype (Url,type); Eg:intent.setDataAndType (URL, "Audio/mp3"); URL Audio file path startactivity (intent);
Second, use Audiotrack to play audio
Audiotrack can only be used to play raw audio (PCM)
Play Audio (PCM) public void Play () {DataInputStream Dis=null;try {//read sound from audio file dis=new DataInputStream (new Bufferedinput Stream (New FileInputStream (Recordingfile))); } catch (FileNotFoundException e) {e.printstacktrace (); }//Minimum buffer int buffersizeinbytes=audiotrack.getminbuffersize (Samplerateinhz,audioformat.channel_out_mono, Audioformat.encoding_pcm_16bit);//Create Audiotrack objects in sequence: stream type, sample rate (consistent with acquisition), Audio channel (acquisition is in play out), quantization bit, minimum buffer, mode player= New Audiotrack (audiomanager.stream_music,samplerateinhz,audioformat.channel_out_mono,audioformat.encoding_pcm_ 16BIT, Buffersizeinbytes, Audiotrack.mode_stream); byte[] Data =new byte [buffersizeinbytes];p layer.play ();// Start playback while (true) {int i=0; try {while (dis.available () >0&&i<data.length) {data[i]=dis.readbyte ();//write Byte when recording Then read the readbyte to correspond to each other i++;}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Player.write (data,0,data.length); if (i!=buffersizeinbytes)//indicates that the read is done {Player.stOP ();//Stop playing player.release ();//release resource break; }}}Here is the key code to play PCM, complete demo at the end of this article will give the corresponding link! The main is to read the data from the file into the array, and then write to the Audiottrack, and then Audiotrack will play it, LeeI! =buffersizeinbytesDetermine if it is finished reading (at the end of the file).
Third, use MediaPlayer for audio playback.
MediaPlayer is a powerful Android system built-in class that not only plays audio but also plays video. The most common methods are:
Start () play pause () Pause play stop () stop play Prepareasync ()/prepare () Start preparation
GetCurrentPosition () Current playback position getduration () file total length of time seekto (int position) position playback
The sample code demonstrates the use of MediaPlayer and Seekbar for audio playback, pause, drag fast forward playback, and so on. Effect (the complete code in the comments can be downloaded Mediaplayerdemo)
Layout file:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:backg round= "@drawable/background" tools:context= "${relativepackage}.${activityclass}" > <textview android:l Ayout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Sky City theme Song (Hayao Miyazaki)" Android:t Extcolor= "#F8F8F8" android:textsize= "18SP" android:ellipsize= "marquee" android:layout_centerinparent= "True"/> <linearlayout android:layout_width= "match_parent" android:layout_height= "wrap _content "android:layout_marginleft=" 5DP "android:layout_marginright=" 5DP "Android:layout_marginbotto M= "5DP" android:layout_above= "@+id/bottom" android:gravity= "center_vertical" > <textview Android:id= "@+id/left" Android:Layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "00:00" Android:textCol Or= "#F8F8F8"/> <seekbar android:id= "@+id/seek" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:layout_weight= "1" android:enabled= "false"/> <textview android:id= "@+id/right" android:layout_width= "wrap_content" android:layout_height= "Wra P_content "android:text=" 00:00 "android:textcolor=" #F8F8F8 "/> </LinearLayout> <linearlayout android:id= "@+id/bottom" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:layout_alignparentbottom= "true" android:layout_marginbottom= "5DP" Android:orie ntation= "Horizontal" > <button android:id= "@+id/start" android:layout_width= "0 DP "Android:layout_height= "Wrap_content" android:layout_weight= "1" android:text= "Play" Android:textcolor = "#F8F8F8" android:textsize= "14sp" android:enabled= "false"/> <butto n android:id= "@+id/stop" android:layout_width= "0DP" android:layout_height= "Wrap_content" android:layout_weight= "1" android:text= "pause" android:textsize= "14SP" android:t Extcolor= "#F8F8F8" android:enabled= "false"/> </LinearLayout> </relativela Yout>
Initialize MediaPlayer
Massetmanager=getassets (); try {afd=massetmanager.openfd ("Sky.mp3");//create Assetfiledescriptor file for Sky City } catch ( IOException e) {e.printstacktrace (); LOG.E (TAG, "Create Assetfiledescriptor exception, see if root blessing exists");} Mmediaplayer=new MediaPlayer (); try {//Set the playback source, and of course there are other overloaded methods Eg:setdatasource (String path) path can make a network path or a local path. Network memory plus permission Mmediaplayer.setdatasource (Afd.getfiledescriptor ()); } catch (Exception e) {e.printstacktrace (); LOG.E (TAG, "Set playback source exception");} Mmediaplayer.prepareasync (); MediaPlayer started to get ready for asynchronous, and prepare () this is synchronous.
MediaPlayer Setting the appropriate listener
Seek.setmax (100);//Set length of Seek.setonseekbarchangelistener (this);//Set Seekbar slide listener Mmediaplayer.setonpreparedlistener (this);//Set Ready to listen Mmediaplayer.setoncompletionlistener (this);//Set playback complete
End slide @Overridepublic void Onstoptrackingtouch (SeekBar SeekBar) { int a= (int) ((sum/100.0) * ( Seekbar.getprogress ())); Mmediaplayer.seekto (a); The units received by the Seekto method are: milliseconds handler.sendemptymessage (START);//Update Seekbar}
@Override public void onprepared (MediaPlayer MP) { //readiness to complete start.setenabled (true); Stop.setenabled (true); Seek.setenabled (true); Sum=mmediaplayer.getduration (); Right.settext (Formattime (sum/1000)); }
Playback complete @overridepublic void Oncompletion (MediaPlayer MP) {Start.settext ("play"); seek.setprogress (0); Mmediaplayer.seekto (0);}
Handler Update the status of Seekbar:
Private Handler handler=new Handler () {@Overridepublic void Handlemessage (Message msg) {switch (msg.what) { Case 1:{ int current=mmediaplayer.getcurrentposition ();//the unit that gets the value is the millisecond int prass= (int) (current/(sum*1.0) *100 ); Left.settext (Formattime (current/1000)); Seek.setprogress (Prass); if (!pause) { handler.sendemptymessagedelayed (1,1000);//1 Seconds to update } break ; Case 0:{ //stop updating pause=true; break; } Default:break;}} ;
1. It is easy to confuse the difference between the pause method and the Stop method: All 2 methods allow the audio to stop.
After you call the pause method, you want to hear the sound again directly after you call the Start method. After calling the Stop method to stop the audio, after calling the Start method again, it will not play, first call the Prepareasync or prepare method, then the public void onprepared (MediaPlayer MP) Callback method will not play until the Start method is called.
The 2.start method is ready to be recalled in public void Onprepared (MediaPlayer MP).
3. Remember stop when not using MediaPlayer, and release the associated resources. (This example is called in the OnDestroy method of the activity)
is the MediaPlayer state and method Flowchart:
Iv. Remarks:
Audiotrack Play Pcmdemo If you are unfamiliar with the audio collection in the demo, you can check the Android audio capture
Mediaplayerdemo (play audio with MediaPlayer)
Android Audio Playback