Android 多媒体 播放音视频

1.播放音频

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<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、播放视频 **

与播放音频基本类似

<VideoView
    android:id="@+id/videoView"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_margin="10dp"/>
  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();
    }
}

界面:

播放多媒体文件.jpg

posted @ 2017-09-05 17:22  -Tiger  阅读(288)  评论(0编辑  收藏