音频:MediaPlayer
1.方法列表
方法名 |
作用 |
setDataSource() |
设置音频文件位置 |
prepare() |
播放前准备工作 |
start() |
开始/继续播放 |
pause() |
暂停播放 |
reset() |
重置播放器 |
seekTo() |
跳转到指定位置播放 |
stop() |
停止播放,且该实例无法再次播放音频 |
release() |
释放MediaPlayer资源,onDestory时调用 |
isPlaying() |
返回boolean,是否正在播放 |
getDuration() |
获取音频时长 |
2.SampleCode
public class MediaPlayerActivity extends AppCompatActivity implements View.OnClickListener {
private MediaPlayer mediaPlayer = new MediaPlayer();
private Button play_Button;
private Button stop_Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
initView();
if (checkPermission()) {
initMediaPlayer();
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
private void initView() {
play_Button = findViewById(R.id.button_play);
stop_Button = findViewById(R.id.button_stop);
play_Button.setOnClickListener(this);
stop_Button.setOnClickListener(this);
}
private void initMediaPlayer() {
try {
File file = new File(Environment.getExternalStorageDirectory(), "music.mp3");
mediaPlayer.setDataSource(file.getPath()); //locate file path for media player
mediaPlayer.prepare(); //prepare media player
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean checkPermission() {
return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
@Override
protected void onDestroy() {
super.onDestroy();
//release resources
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_play:
if (mediaPlayer.isPlaying()) {
//switch to pause
mediaPlayer.pause();
play_Button.setText("play");
} else {
mediaPlayer.start();
play_Button.setText("pause");
}
break;
case R.id.button_stop:
if (mediaPlayer.isPlaying()) {
mediaPlayer.reset();
initMediaPlayer();
}
break;
default:
break;
}
}
@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 {
//permission not granted
finish();
}
break;
default:
return;
}
}
}
视频:VideoView
此处的调用基本与MediaPlayer一致,只列一下该view的常用方法:
1.方法列表
方法名 |
作用 |
setVideoPath() |
设置视频文件位置 |
start() |
开始/继续播放 |
pause() |
暂停播放 |
resume() |
重头播放 |
seekTo() |
跳转到指定位置播放 |
isPlaying() |
返回boolean,是否正在播放 |
getDuration() |
获取视频时长 |