Learn the Android<mediaplayer player component from scratch (play audio). 48 .>

Source: Internet
Author: User

Playing video and audio in the win computer often uses the WindowsMediaPlayer player in the computer, while in Android, the audio and video are also played using the MediaPlayer player.

is the life cycle of MediaPlayer.



dle State: When a MediaPlayer object is instantiated with the keyword new or the Reset () method in the calling class is entered into this state; End State: when the release () method is called, it enters this state, freeing up all the hardware and software resources that are consumed and no longer entering any other state; initialized Status: When the MediaPlayer object is set up to play the media file (Setdatasource ()) to enter this state; Prepared Status: enter into pre-play State (Prepare (), Prepareasync ()), enter this status indicates that the current media file does not have any problems, you can use Onpreparedlistener to listen to this state ; If the user calls the prepare () Method (synchronous), the MediaPlayer object has entered the Prepared State; If the user invokes the Prepareasync () Method (async), the MediaPlayer object is entered into the Preparing Status and returns, while the internal playback engine continues to perform an unfinished preparation operation. started Status: media playback is in progress (Start ()), at which point the Seekto () method can be used to specify the location of the media playback; paused Status: Use the paused state in the started state can pause the playback of the MediaPlayer, after the pause can be changed back to started state by the start () method, continue to play; Stop State: the Stop () method can be used to stop MediaPlayer playback in the started and paused states, and you can use prepare () if you want to replay it in the stop state. and the Prepareasync () method enters the ready state. playbackcompleted Status: When the media is finished, it will enter this state, the user can use Oncompletionlistener to listen to this state, at this time can use the start () method to replay, You can also use the Stop () method to stop playback, or use the Seekto () method to reposition the playback position;Error Status: when there are some errors in the user playback operation (file format is incorrect, the playback file is too large, etc.), the user can use Onerrorlistener to listen to this state, If MediaPlayer enters this state, it can use the Reset () method to return to the idle state;

Here's a simple example to use for audio playback


Xim file

<span style= "FONT-SIZE:18PX;" ><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:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ".        Mainactivity "> <imagebutton android:id=" @+id/imagebutton1 "android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_alignparenttop = "true" android:layout_margintop= "16DP" android:src= "@drawable/play"/> <imagebutton Android : id= "@+id/imagebutton3" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android Oid:layout_alignParentright= "true" android:layout_aligntop= "@+id/imagebutton2" android:src= "@drawable/stop"/> <Ima Gebutton android:id= "@+id/imagebutton2" android:layout_width= "wrap_content" android:layout_height= "WR Ap_content "android:layout_aligntop=" @+id/imagebutton1 "android:layout_centerhorizontal=" true "Androi d:src= "@drawable/pause"/> <imagebutton android:id= "@+id/imagebutton4" android:layout_width= "Wrap_c Ontent "android:layout_height=" wrap_content "android:layout_alignleft=" @+id/imagebutton1 "Android:lay out_below= "@+id/imagebutton1" android:layout_margintop= "19DP" android:src= "@drawable/vioceup"/> <T Extview android:id= "@+id/textview1" android:layout_width= "wrap_content" android:layout_height= "Wrap_c Ontent "android:layout_aligntop=" @+id/imagebutton4 "android:layout_centerhorizontal=" true "Android:la   yout_margintop= "14DP"     Android:text= "Waiting to play audio file" android:textappearance= "? Android:attr/textappearancemedium"/> <imagebutton Android:id= "@+id/imagebutton5" android:layout_width= "wrap_content" android:layout_height= "wrap_content "Android:layout_alignleft=" @+id/imagebutton3 "android:layout_alignright=" @+id/imagebutton3 "Android: layout_aligntop= "@+id/imagebutton4" android:src= "@drawable/voicedown"/></relativelayout></span>


Java files

<span style= "FONT-SIZE:18PX;" >package Com.example.mediaplayer;import Java.io.ioexception;import Android.app.activity;import Android.content.context;import Android.media.audiomanager;import Android.media.mediaplayer;import Android.media.mediaplayer.oncompletionlistener;import Android.os.bundle;import Android.view.View;import Android.widget.imagebutton;import Android.widget.textview;import Android.widget.toast;public class MainActivity Extends Activity {Private ImageButton play, stop, pause, Voiceup, voicedown;//set imagebuttonprivate TextView info;//settings information Display Bar private MediaPlayer MediaPlayer = null;//Create MediaPlayer object private Boolean Pauseflag = false;// Set playback status for play @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);p lay = (ImageButton) This.findviewbyid (r.id.imagebutton1); stop = ( ImageButton) This.findviewbyid (r.id.imagebutton3);p ause = (ImageButton) This.findviewbyid (R.id.imagebutton2); Voicedown = (ImagEbutton) This.findviewbyid (r.id.imagebutton5); voiceup = (ImageButton) This.findviewbyid (r.id.imagebutton4); info = ( TextView) This.findviewbyid (R.ID.TEXTVIEW1);//Get Volume Action object final Audiomanager audio = (Audiomanager) Super.getsystemservice (Context.audio_service)///Play button monitor Play.setonclicklistener (new View.onclicklistener () {@ overridepublic void OnClick (View v) {//TODO auto-generated method stub//Instantiate Mediaplay Object MediaPlayer = Mediaplayer.create ( Mainactivity.this, R.raw.media);//Set the listen operation to playback MainActivity.this.mediaPlayer.setOnCompletionListener (new Oncompletionlistener () {@Overridepublic void oncompletion (MediaPlayer MP) {//TODO auto-generated method stub// Release the Resource Mediaplayer.release () after playback is complete;//Set the status of the play button play.setenabled (true);}); if (MediaPlayer! = null) {mediaplayer.stop ();} try {//Enter playback equipment status Mediaplayer.prepare ();} catch (IllegalStateException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace (); Toast.maketext (MainacTivity.this, "Playback error", 2). Show (); Start playing audio Mediaplayer.start (); Info.settext ("Playing music");//playback cannot continue to play on the song Play.setenabled (false);}); /Pause.setonclicklistener for pause playback (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated method stubif (MediaPlayer! = null) {//To determine the paused state, implement click-to-play and click Pause again if (Pauseflag) {Mediaplayer.start (); Pauseflag = False;info.settext ("playing music"); else {mediaplayer.pause (); Info.settext ("Stop playing music"); Pauseflag = True;}}}); /Listen to stop button Stop.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated method stubif (MediaPlayer! = null) {mediaplayer.stop (); Info.settext ("Stop playing audio");p lay.setenabled (True);}}); Monitor for volume down Voicedown.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated method Stubaudio.adjustvolume (audiomanager.adjust_lower, 0); Toast.maketext (Mainactivity.this, "Volume Down", 1). Show ();}); /monitor for volume increase voiceup.setonclicklistener (new view.onclicKlistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubaudio.adjustvolume ( Audiomanager.adjust_raise, 0); Toast.maketext (Mainactivity.this, "volume Increase", 1). Show ();}});}} </span>

The use of MediaPlayer can be very convenient to control the audio, you can refer to the API to achieve more features.


Next forecast: MediaPlayer system player (play video)

Learn the Android<mediaplayer player component from scratch (play audio). 48 .>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.