播放音视频---MediaPlayer、VideoView

实现了简单的音视频功能。

前提条件,申请读取SD卡的权限,Android6.0及以上还要记得动态申请哦(放于文章最后)!!!

1.播放音频

功能:播放(续播)、暂停、停止。
播放音视频---MediaPlayer、VideoView_第1张图片
1.布局xml:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_margin="5dp"
            android:id="@+id/btn_paly"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="play"/>

        <Button
            android:layout_margin="5dp"
            android:id="@+id/btn_pause"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="pause"/>

        <Button
            android:layout_margin="5dp"
            android:id="@+id/btn_stop"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="stop"/>
    LinearLayout>

LinearLayout>

2.activity代码:

public class ActPlayMedia extends AppCompatActivity{
    @BindView(R.id.btn_paly)
    Button btnPaly;
    @BindView(R.id.btn_pause)
    Button btnPause;
    @BindView(R.id.btn_stop)
    Button btnStop;

    private MediaPlayer mediaPlayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_mediaplayer);
        ButterKnife.bind(this);
        initMediaPlayer();
    }

    /**
     * 初始化MediaPlayer
     */
    public void initMediaPlayer(){
        try{
            File sdDir = Environment.getExternalStorageDirectory();
            File folderDir = new File(sdDir.getPath() + "/xxx");
            if (!folderDir.exists()) {
                folderDir.mkdir();
            }
            File file = new File(folderDir.getAbsolutePath(),"music.mp3");
            if(file.exists()){
                mediaPlayer.setDataSource(file.getPath());//指定音频文件路径
                mediaPlayer.prepare();//让mediaPlayer进入准备状态
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @OnClick({R.id.btn_paly, R.id.btn_pause, R.id.btn_stop})
    public void onViewClicked(View view) {
        switch (view.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.reset();//停止播放
                    initMediaPlayer();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer.reset();//释放资源
        }
    }
}

2.播放视频

功能:播放(续播)、暂停、重播。
播放音视频---MediaPlayer、VideoView_第2张图片
1.布局xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_margin="5dp"
            android:id="@+id/btn_paly"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="play"/>

        <Button
            android:layout_margin="5dp"
            android:id="@+id/btn_pause"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="pause"/>

        <Button
            android:layout_margin="5dp"
            android:id="@+id/btn_replay"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="replay"/>
    LinearLayout>

    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"/>

LinearLayout>

2.activity代码

public class ActPlayVideo extends AppCompatActivity {

    @BindView(R.id.btn_paly)
    Button btnPaly;
    @BindView(R.id.btn_pause)
    Button btnPause;
    @BindView(R.id.btn_replay)
    Button btnReplay;
    @BindView(R.id.video_view)
    VideoView videoView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_playvideo);
        ButterKnife.bind(this);
        initVideoPath();
    }

    public void initVideoPath(){
        File sdDir = Environment.getExternalStorageDirectory();
        File folderDir = new File(sdDir.getPath() + "/xxx");
        if (!folderDir.exists()) {
            folderDir.mkdir();
        }
        File file = new File(folderDir.getAbsolutePath(),"video.mp4");
        if(file.exists()){
            videoView.setVideoPath(file.getPath());//指定视频文件的路径
        }
    }

    @OnClick({R.id.btn_paly, R.id.btn_pause, R.id.btn_replay})
    public void onViewClicked(View view) {
        switch (view.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_replay:
                if(videoView.isPlaying()){
                    videoView.resume();//重新播放
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(videoView != null){
            videoView.suspend();//释放资源
        }
    }
}

3.申请SD卡读取权限

1.配置文件申明:

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

2.动态申请

private boolean hadPermission = false;

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,};//SD卡读写的权限
    private static final int REQUEST_EXTERNAL_STORAGE = 21;
    private final static int RESULT_PERMISSION = 1001;

 /**
     * 请求权限
     */
    public void verifyStoragePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int i = ContextCompat.checkSelfPermission(MainActivity.this, PERMISSIONS_STORAGE[0]);
            int j = ContextCompat.checkSelfPermission(MainActivity.this, PERMISSIONS_STORAGE[1]);
            if (i != PackageManager.PERMISSION_GRANTED || j != PackageManager.PERMISSION_GRANTED) {
                //权限还没有授予,进行申请权限
                startRequestPermission();
            } else {
                hadPermission = true;
            }
        } else {
            hadPermission = true;
        }
    }

    /**
     * 开始提交请求权限
     */
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
    }

    /**
     * 用户权限 申请 的回调方法
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_EXTERNAL_STORAGE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults.length != 0) {
                    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                        // 判断用户是否点击了不再提醒。(检测该权限是否还可以申请)
                        boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                        if (!b) {
                        } else {
                        }
                        hadPermission = false;
                    } else {
                        hadPermission = true;
                    }
                }
            }
        }
    }

你可能感兴趣的:(Android之路)