本篇主要介绍使用Mediaplayer实现mp3简易音乐播放器,程序运行界面如下
下面是代码实现,因为代码比较简单,注释已经比较明确了。
public class PlayActivity extends Activity implements OnClickListener { private EditText filenameText; // 音频播放的主要类 private MediaPlayer mediaPlayer; private String filename; // 记录播放位置 private int position; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); filenameText = (EditText) this.findViewById(R.id.filename); mediaPlayer = new MediaPlayer(); Button playButton = (Button) this.findViewById(R.id.play); Button pauseButton = (Button) this.findViewById(R.id.pause); Button resetButton = (Button) this.findViewById(R.id.reset); Button stopButton = (Button) this.findViewById(R.id.stop); playButton.setOnClickListener(this); pauseButton.setOnClickListener(this); resetButton.setOnClickListener(this); stopButton.setOnClickListener(this); } //按钮点击事件 @Override public void onClick(View v) { filename = filenameText.getText().toString(); Button button = (Button) v; try { switch (v.getId()) { case R.id.play: play(); break; case R.id.pause: if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); button.setText("继续"); } else { mediaPlayer.start(); button.setText("暂停"); } break; case R.id.reset: //重播 if (mediaPlayer.isPlaying()) { mediaPlayer.seekTo(0); } else { play(); } break; case R.id.stop: //停止 if (mediaPlayer.isPlaying()) mediaPlayer.stop(); break; } } catch (Exception e) { e.printStackTrace(); } } //当播放界面因为来电或者Home键进入后台调用,保存文件名与播放位置,便于恢复 @Override protected void onSaveInstanceState(Bundle outState) { outState.putString("filename", filename); outState.putInt("position", position); super.onSaveInstanceState(outState); } //当界面进入后台被销毁,然后再次进入的时候被调用,在这里回复上次的播放状态 @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { this.filename = savedInstanceState.getString("filename"); this.position = savedInstanceState.getInt("position"); super.onRestoreInstanceState(savedInstanceState); } //当界面被遮挡,暂停播放 @Override protected void onPause() { if (mediaPlayer.isPlaying()) { position = mediaPlayer.getCurrentPosition(); mediaPlayer.stop(); } super.onPause(); } //当界面进入可交互状态,判断时候有文件名和播放记录,若有,则继续上次开始播放 @Override protected void onResume() { if (position > 0 && filename != null) { try { play(); mediaPlayer.seekTo(position); position = 0; } catch (IOException e) { e.printStackTrace(); } } super.onResume(); } //销毁资源 @Override protected void onDestroy() { mediaPlayer.release(); super.onDestroy(); } //播放方法的核心实现 private void play() throws IOException { //获取播放文件名 File audioFile = new File(Environment.getExternalStorageDirectory(), filename); //重置状态 mediaPlayer.reset(); //设置数据源 mediaPlayer.setDataSource(audioFile.getAbsolutePath()); //进行前期硬件准备 mediaPlayer.prepare(); //开始播放 mediaPlayer.start(); } }
原文地址:http://blog.csdn.net/zhaokaiqiang1992/article/details/30994735