PackageCom.zhangbz.musicplayer;ImportJava.io.File;Importandroid.app.Activity;ImportAndroid.media.AudioManager;ImportAndroid.media.MediaPlayer;ImportAndroid.media.MediaPlayer.OnCompletionListener;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {PrivateEditText Et_path; PrivateMediaPlayer MediaPlayer; PrivateButton Bt_play, Bt_pause, Bt_stop, Bt_replay; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Et_path=(EditText) Findviewbyid (R.id.et_path); Bt_play=(Button) Findviewbyid (R.id.bt_play); Bt_pause=(Button) Findviewbyid (r.id.bt_pause); Bt_replay=(Button) Findviewbyid (R.id.bt_replay); Bt_stop=(Button) Findviewbyid (r.id.bt_stop); } /*** Play *@paramView*/ Public voidPlay (view view) {String filepath=Et_path.gettext (). toString (). Trim (); File File=NewFile (filepath); if(File.exists ()) {Try{MediaPlayer=NewMediaPlayer (); Mediaplayer.setdatasource (filepath);//set the data source for playbackMediaplayer.setaudiostreamtype (Audiomanager.stream_music); Mediaplayer.prepare ();//ready to start playback, the logic of playback is the C code executed on the new thread. Mediaplayer.start (); Bt_play.setenabled (false); Mediaplayer.setoncompletionlistener (NewOncompletionlistener () { Public voidoncompletion (MediaPlayer arg0) {bt_play.setenabled (true); } }); } Catch(Exception e) {Toast.maketext ( This, "Playback failed", 0). Show (); E.printstacktrace (); } } Else{Toast.maketext ( This, "file does not exist, please check the file path", 0). Show (); } } /*** Pause *@paramView*/ Public voidPause (view view) {if("Continue". Equals (Bt_pause.gettext (). toString (). Trim ())) {Mediaplayer.start (); Bt_pause.settext (Pause); return; } if(MediaPlayer! =NULL&&mediaplayer.isplaying ()) {Mediaplayer.pause (); Bt_pause.settext (Continue to); } } /*** Stop *@paramView*/ Public voidStop (view view) {if(MediaPlayer! =NULL&&mediaplayer.isplaying ()) {mediaplayer.stop (); Mediaplayer.release (); MediaPlayer=NULL; } bt_pause.settext (Pause); Bt_play.setenabled (true); } /*** Replay *@paramView*/ Public voidReplay (view view) {if(MediaPlayer! =NULL&&mediaplayer.isplaying ()) {Mediaplayer.seekto (0); } Else{play (view); } bt_replay.settext (Pause); }}
Android Music player Simple implementation