说说 Android 中如何操作音频与视频文件

1 音频

在 Android 中播放音频文件用的是 MediaPlayer 类,它提供了一些较为常用的控制方法。

方法 说明
setDataSource() 指定音频文件位置。
prepare() 准备播放之前完成准备工作。
start() 开始或继续播放音频。
pause() 暂停播放音频。
reset() 将 MediaPlayer 对象重置到刚刚创建的状态。
seekTo() 从指定位置开始播放。
stop() 停止播放。调用后,MediaPlayer 对象将无法再播放。
release() 释放与 MediaPlayer 对象相关的资源。
isPlaying() 判断是否正在播放。
getDuration() 获取音频文件的时长。

工作流程如下:

  1. 创建 MediaPlayer 对象。
  2. 设置音频文件路径。
  3. 进入准备状态。
  4. 开始播放音频。

布局文件:

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

    <Button
        android:id="@+id/play"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="播放" />

    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="暂停" />

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="停止" />


</LinearLayout>

活动类:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private MediaPlayer player = new MediaPlayer();

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

        //设置点击监听器
        findViewById(R.id.play).setOnClickListener(this);
        findViewById(R.id.pause).setOnClickListener(this);
        findViewById(R.id.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 {
            init();
        }
    }

    /**
     * 初始化
     */
    private void init() {
        try {
            File file = new File(Environment.getExternalStorageDirectory(), "xxx.mp3");
            player.setDataSource(file.getPath());//指定文件路径
            player.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){
                    init();
                }else{
                    Toast.makeText(this, "被拒绝啦", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.play:
                if(!player.isPlaying()){//开始播放
                    player.start();
                }
                break;
            case R.id.pause:
                if(player.isPlaying()){//暂停
                    player.pause();
                }
                break;
            case R.id.stop:
                if(player.isPlaying()){//停止
                    player.reset();
                    init();
                }
                break;
            default:
                break;
        }
    }

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

这里我们申请了权限,因为为了播放音频文件,必须拥有访问 SD 卡权限。

记得在 AndroidManifest.xml 文件中声明需要用到的权限:

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

权限申请

这样,我们的 APP 就可以控制我们想要播放的文件啦,是不是很简单呀 O(∩_∩)O哈哈~

2 视频

Android 中可以使用 VideoView 来显示与控制视频,它以下这些常用的方法:

方法 说明
setVideoPath() 设置视频文件的位置。
start() 开始和继续播放。
pause() 暂停播放。
resume() 从头开始播放。
seekTo() 从指定位置开始播放。
isPlaying() 判断当前是否正在播放。
getDuration() 获取视频文件的时长。

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    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:id="@+id/play"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="播放" />

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

        <Button
            android:id="@+id/replay"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="重播" />


    </LinearLayout>

    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

扫描二维码关注公众号,回复: 1529703 查看本文章

在这个布局文件中,第一行放置了三个按钮,分别用于控制视频的播放、暂停和重播;然后在下一行放置了一个 VideoView 。

活动类:

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 = (VideoView) findViewById(R.id.video_view);

        //设置点击监听器
        findViewById(R.id.play).setOnClickListener(this);
        findViewById(R.id.pause).setOnClickListener(this);
        findViewById(R.id.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 {
            init();
        }
    }

    /**
     * 初始化
     */
    private void init() {
        try {
            File file =
                    new File(Environment.getExternalStorageDirectory(), "xxx.mp4");
            videoView.setVideoPath(file.getPath());//指定文件路径
        } catch (Exception 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) {
                    init();
                } else {
                    Toast.makeText(this, "被拒绝啦", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }


    @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:
                if (videoView.isPlaying()) {//停止
                    videoView.resume();
                }
                break;
            default:
                break;
        }
    }

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

最后记得声明权限哦:

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

启动 APP,就可以播放视频咯O(∩_∩)O哈哈~

VideoView 底层其实是使用 MediaPlayer 实现的哦。

注意:它支持以下这些视频格式:

 Video H.263 X X 3GPP (.3gp) and MPEG-4 (.mp4)   H.264 AVC X 3GPP (.3gp) and MPEG-4 (.mp4)   MPEG-4 SP X 3GPP (.3gp)

一般用来播放游戏的片头动画,或者应用的视频宣传。

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/80556277