第一行代码学习笔记
1、创建一个 MediaPlayer 对象
2、调用 setDataSource()方法来设置音频文件的路径
3、 控制方法,prepare(),start(),pause(), reset()
4、播放Video方法类似,需要添加VideoView
public class MainActivity extends Activity implements OnClickListener {
private Button play; private Button pause; private Button stop; private MediaPlayer mediaPlayer = new MediaPlayer(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); play = (Button) findViewById(R.id.play); pause = (Button) findViewById(R.id.pause); stop = (Button) findViewById(R.id.stop); play.setOnClickListener(this); pause.setOnClickListener(this); stop.setOnClickListener(this); initMediaPlayer(); } private void initMediaPlayer() { try { File file = new File(Environment.getExternalStorageDirectory(), "music.mp3"); //设定路径 mediaPlayer.setDataSource(file.getPath()); mediaPlayer.prepare(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.play: if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); } break; case R.id.pause: if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); } break; case R.id.stop: if (mediaPlayer.isPlaying()) { mediaPlayer.reset(); initMediaPlayer(); } break; default: break; } } @Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } }
}