Android 多媒体(三)——播放多媒体文件

新建一个空项目 day15_PlayAudioTest

一、播放音频

播放音频一般使用MediaPlayer类实现:

  • setDataSource():选择要播放的音频文件
  • prepare():开始播放前调用这个完成准备工作
  • start():开始或继续播放音频
  • pause():暂停播放
  • reset():停止并重置
  • seekTo():跳转到指定时间
  • stop():停止播放,之后无法再播放
  • release():释放音频资源
  • isPlaying():判断当前播放状态
  • getDuration():获取音频时长

1、主布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/play"
        android:text="播放"/>
    
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/pause"
        android:text="暂停"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/stop"
        android:text="停止"/>

</LinearLayout>

2、主活动

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private MediaPlayer mediaPlayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button play = findViewById(R.id.play);
        Button pause = findViewById(R.id.pause);
        Button stop = findViewById(R.id.stop);
        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        stop.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();
        }
    }

    private void initMediaPlayer() {
        try {
            File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "TGA2018串烧.mp3");
            mediaPlayer.setDataSource(file.getPath());
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] 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 v) {
        switch (v.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:
                mediaPlayer.reset();
                initMediaPlayer();
                break;
            default:
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if( mediaPlayer!= null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}

3、权限

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

    <application
        android:requestLegacyExternalStorage="true"
        ...

不截图了,反正音乐你们也听不见

二、播放视频

新建一个空项目 day15_PlayVideoTest

播放视频一般使用VideoView类实现:

  • setVideoPath:选择要播放的视频文件
  • start():开始或继续播放视频
  • pause():暂停播放
  • resume():重头播放
  • seekTo():跳转到指定时间
  • isPlaying():判断当前播放状态
  • getDuration():获取视频时长

1、主布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/play"
            android:layout_weight="1"
            android:text="播放"/>
        
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/pause"
            android:layout_weight="1"
            android:text="暂停"/>
        
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/replay"
            android:layout_weight="1"
            android:text="重播"/>
        
    </LinearLayout>
    
    <VideoView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/video_view"/>

</LinearLayout>

2、主活动

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private VideoView videoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videoView = findViewById(R.id.video_view);
        Button play = findViewById(R.id.play);
        Button pause = findViewById(R.id.pause);
        Button replay = findViewById(R.id.replay);
        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        replay.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 {
            initVideoPath();
        }
    }

    private void initVideoPath() {
        File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "瑞克和莫蒂第四季第三集.mp4");
        videoView.setVideoPath(file.getPath());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initVideoPath();
                } else {
                    Toast.makeText(this, "权限呢???", Toast.LENGTH_SHORT).show();
                    finish();
                }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                if (!videoView.isPlaying()) {
                    videoView.start();
                }
                break;
            case R.id.pause:
                if (videoView.isPlaying()) {
                    videoView.pause();
                }
                break;
            case R.id.replay:
                videoView.resume();
                break;
            default:
        }
    }

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

3、权限

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

<application
    android:requestLegacyExternalStorage="true"

4、运行

在这里插入图片描述

5、报错

在Android7.0以上的设备会有这个警告:

W/MediaPlayer: Couldn't open /storage/emulated/0/Download/瑞克和莫蒂第四季第三集.mp4
    java.io.FileNotFoundException: No content provider: /storage/emulated/0/Download/瑞克和莫蒂第四季第三集.mp4
        at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1673)
        at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1503)
        at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1420)
        at android.media.MediaPlayer.attemptDataSource(MediaPlayer.java:1101)
        at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1073)
        at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1097)
        at android.widget.VideoView.openVideo(VideoView.java:412)
        at android.widget.VideoView.resume(VideoView.java:819)
        at com.example.day15_playvideotest.MainActivity.onClick(MainActivity.java:75)
        at android.view.View.performClick(View.java:7140)
        at android.view.View.performClickInternal(View.java:7117)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27351)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

其中提示No content provider,这就需要借助内容提供器了,参考文章:《Android 多媒体(二)——调用摄像头和相册》
《没有内容提供者》
但这里就播放个视频,又不用自己写播放器,没那必要了

发布了166 篇原创文章 · 获赞 14 · 访问量 9105

猜你喜欢

转载自blog.csdn.net/qq_41205771/article/details/104326612