Android 多媒体 播放音视频

1.播放音频

因为涉及到读取文件,所以需要申请权限

<1>首先动态申请权限

    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission
            .WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, 
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
    } else {
        initVideoPath(); //初始化 MediaPlayer
    }
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    switch (requestCode) {
        case 1:
            if (permissions.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initVideoPath();
            } else {
                Toast.makeText(this, "You denied the permission.", Toast.LENGTH_SHORT).show();
            }
            break;
    }
}

<2>然后初始化 MediaPlayer

   private MediaPlayer mediaPlayer=new MediaPlayer();
    File file=new File("/storage/emulated/0/Download/susic.mp3");
    mediaPlayer.setDataSource(file.getPath()); //指定音频文件路径
    mediaPlayer.prepare(); //让 MediaPlayer 进入到准备状态

<3>设置播放、暂停、停止按钮的点击事件

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_paly:
            if(!mediaPlayer.isPlaying())
                mediaPlayer.start();
            break;
        case R.id.btn_pause:
            if(mediaPlayer.isPlaying())
                mediaPlayer.pause();
            break;
        case R.id.btn_stop:
            if(mediaPlayer.isPlaying())
                mediaPlayer.stop();
            initMediaPlayer();
            break;
    }
}

2、播放视频

与播放音频基本类似

  private VideoView videoView;
  File file=new File(et_path.getText().toString());
  videoView.setVideoPath(file.getPath()); //设置视频路径
  
  //设置 播放、暂停、停止 的点击事件
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_paly:
            if(!videoView.isPlaying())
                videoView.start();
            break;
        case R.id.btn_pause:
            if(videoView.isPlaying())
                videoView.pause();
            break;
        case R.id.btn_stop:
            if(videoView.isPlaying())
                videoView.resume();
            break;
    }
}

释放资源

@Override
protected void onDestroy() {
    super.onDestroy();
    if(videoView!=null){
        videoView.suspend();
    }
}

界面:

Android 多媒体 播放音视频_第1张图片

转载于:https://www.cnblogs.com/-Tiger/p/7479670.html

你可能感兴趣的:(Android 多媒体 播放音视频)