mp3播放器(六)(播放功能实现)
1 package com.example.mp3player00; 2 3 import java.io.File; 4 5 import model.Mp3Info; 6 import android.app.Activity; 7 import android.content.Intent; 8 import android.media.MediaPlayer; 9 import android.net.Uri; 10 import android.os.Bundle; 11 import android.os.Environment; 12 import android.view.View; 13 import android.view.View.OnClickListener; 14 import android.widget.ImageButton; 15 16 public class PlayerActivity extends Activity{ 17 ImageButton startButton=null; 18 ImageButton pauseButton=null; 19 ImageButton stopButton=null; 20 MediaPlayer mediaPlayer=null; 21 private boolean isPlaying=false; 22 private boolean isPause=false; 23 private boolean isReleased=false; 24 Mp3Info mp3Info=null; 25 @Override 26 protected void onCreate(Bundle savedInstanceState) { 27 // TODO Auto-generated method stub 28 super.onCreate(savedInstanceState); 29 setContentView(R.layout.player); 30 Intent intent=getIntent(); 31 mp3Info=(Mp3Info) intent.getSerializableExtra("mp3Info"); 32 startButton=(ImageButton)findViewById(R.id.start); 33 pauseButton=(ImageButton)findViewById(R.id.pause); 34 stopButton=(ImageButton)findViewById(R.id.stop); 35 startButton.setOnClickListener(new startButtonListener()); 36 pauseButton.setOnClickListener(new pauseButtonListener()); 37 stopButton.setOnClickListener(new stopButtonListener()); 38 39 40 } 41 class startButtonListener implements OnClickListener{ 42 43 @Override 44 public void onClick(View arg0) { 45 // TODO Auto-generated method stub 46 if(!isPlaying){//如果不在播放 47 String path=getMp3Path(mp3Info); 48 mediaPlayer=MediaPlayer.create(PlayerActivity.this, Uri.parse("file://"+path)); 49 mediaPlayer.setLooping(false); 50 mediaPlayer.start(); 51 isPlaying=true; 52 isReleased=false; 53 } 54 } 55 56 } 57 class pauseButtonListener implements OnClickListener{ 58 59 @Override 60 public void onClick(View v) { 61 // TODO Auto-generated method stub 62 if(!isPause){ 63 //如果当前不在暂停 64 mediaPlayer.pause(); 65 isPause=true; 66 isPlaying=false; 67 } 68 //如果当前在暂停的状态 69 else{ 70 mediaPlayer.start(); 71 isPause=false; 72 isPlaying=true; 73 } 74 } 75 76 } 77 class stopButtonListener implements OnClickListener{ 78 79 @Override 80 public void onClick(View v) { 81 // TODO Auto-generated method stub 82 if(isPlaying){ 83 if(!isReleased){ 84 mediaPlayer.stop(); 85 mediaPlayer.release();//释放掉资源,当不再使用mediaPlayer 86 isReleased=true; 87 } 88 isPlaying=false; 89 } 90 91 } 92 93 } 94 private String getMp3Path(Mp3Info mp3Info) 95 { 96 String SDCardRoot=Environment.getExternalStorageDirectory().getAbsolutePath(); 97 String Path=SDCardRoot+File.separator+"mp3"+File.separator+mp3Info.getMp3Name(); 98 return Path; 99 100 } 101 102 103 104 105 }
自信与努力 用心坚持