MediaPlayer状态图
State Diagram
Playback control of audio/video files and streams is managed as a state machine. The following diagram shows the life cycle and the states of a MediaPlayer object driven by the supported playback control operations. The ovals represent the states a MediaPlayer object may reside in. The arcs represent the playback control operations that drive the object state transition. There are two types of arcs. The arcs with a single arrow head represent synchronous method calls, while those with a double arrow head represent asynchronous method calls.
第一步:设置权限(很重要,千万别忘了)
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />第二步:按照状态图的顺序调用方法播放歌曲
mButtonPaly.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mButtonPaly.setBackgroundColor(Color.BLUE);
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
Log.d("music",""+Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath());
File filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
File[] files = filesDir.listFiles();
for(File file:files){
Log.d("music",""+file.getAbsolutePath());
}
try {
mediaPlayer.setDataSource(files[0].getAbsolutePath());
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});