添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity.java
private MediaPlayer mediaPlayer = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.play);
Button button1 = findViewById(R.id.pause);
Button button2 = findViewById(R.id.stop);
button.setOnClickListener(this);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//运行时权限处理
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 1);
} else {
initMediaPlayer();//初始化MediaPlayer
}
}
private void initMediaPlayer() {//用户同意授权后会调用
try {
File file = new File(Environment.getExternalStorageDirectory(), "music.mp3"); //SD卡根目录
mediaPlayer.setDataSource(file.getPath()); //指定文件路径
mediaPlayer.prepare();//让MediaPlayer进入到准备状态
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initMediaPlayer();
} else {
Toast.makeText(this, "拒绝权限将无法使用教程", Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
@Override
public void onClick(View view) {
switch (view.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.stop();
initMediaPlayer();
}
break;
default:
break;
}
}
@Override
protected void onDestroy() {//将资源释放
super.onDestroy();
if (mediaPlayer!=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
activity_main.xml
<Button
android:id="@+id/play"
android:textAllCaps="false"
android:text="Paly"
android:layout_width="match_parent"
android:layout_height="wrap_content"></Button>
<Button
android:id="@+id/pause"
android:textAllCaps="false"
android:text="Pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"></Button>
<Button
android:id="@+id/stop"
android:textAllCaps="false"
android:text="Stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"></Button>
网友评论