MediaPlayer播放歌曲

来源:互联网 发布:中原g7 知乎 编辑:程序博客网 时间:2024/06/06 08:31

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();
}
}
});

1 0
原创粉丝点击