VideoView 的简单使用

VideoView 的简单使用, 主要用于播放网络地址, 实现播放, 暂停, 继续, 停止退出, 播放进度显示(没实现拖拽播放)

废话不多说, 看效果

正在播放
在这里插入图片描述
控制按钮
在这里插入图片描述
加载中
在这里插入图片描述

xml布局代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlRootView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    tools:context=".activity.PlayVideoActivity">

    <VideoView
        android:id="@+id/mVideoView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

    <ProgressBar
        android:id="@+id/loadingView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <LinearLayout
        android:id="@+id/llManagerLayout"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_alignParentBottom="true"
        android:background="#5E107CE9"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingLeft="20dp"
        android:paddingRight="20dp">

        <ImageView
            android:id="@+id/ivExit"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:padding="14dp"
            android:src="@mipmap/exit" />

        <ImageView
            android:id="@+id/ivState"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:padding="12dp"
            android:src="@mipmap/stop" />

        <TextView
            android:id="@+id/tvPlayTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            android:singleLine="true"
            android:text="00:00"
            android:textAllCaps="false"
            android:textColor="#FFFFFF"
            android:textSize="14sp" />

        <ProgressBar
            android:id="@+id/pbProgress"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/tvTotalTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            android:singleLine="true"
            android:text="00:00"
            android:textAllCaps="false"
            android:textColor="#FFFFFF"
            android:textSize="14sp" />

    </LinearLayout>

</RelativeLayout>

java代码

package com.geaosu.video.activity;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.blankj.utilcode.util.ToastUtils;
import com.geaosu.video.R;
import com.geaosu.video.base.BaseActivity;
import com.geaosu.video.manager.UrlManager;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 播放视频
 */
public class PlayVideoActivity extends BaseActivity {
    @BindView(R.id.rlRootView)
    RelativeLayout rlRootView;
    @BindView(R.id.mVideoView)
    VideoView mVideoView;
    @BindView(R.id.loadingView)
    ProgressBar loadingView;

    @BindView(R.id.llManagerLayout)
    LinearLayout llManagerLayout;
    @BindView(R.id.ivExit)
    ImageView ivExit;
    @BindView(R.id.ivState)
    ImageView ivState;
    @BindView(R.id.tvPlayTime)
    TextView tvPlayTime;
    @BindView(R.id.pbProgress)
    ProgressBar pbProgress;
    @BindView(R.id.tvTotalTime)
    TextView tvTotalTime;

    public static void open(Context mContext, String videoPath) {
        Intent intent = new Intent(mContext, PlayVideoActivity.class);
        intent.putExtra("videoPath", videoPath);
        mContext.startActivity(intent);
    }

    @Override
    protected int attachLayout() {
        return R.layout.activity_play_video;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 抖音短视频
//        String mUrl = "https://aweme.snssdk.com/aweme/v1/playwm/?video_id=v0300f1b0000btp92lfcmfsqs3dmqt70&ratio=720p&line=0";
        // 酒醉的蝴蝶-DJ
        String mUrl = "https://vd4.bdstatic.com/mda-kdj0c2ux79k3g9xy/v1-cae/sc/mda-kdj0c2ux79k3g9xy.mp4?auth_key=1601431362-0-0-6c01bebfc0882018d1079af0e6c1e883&bcevod_channel=searchbox_feed&pd=1&pt=3";
//         String mUrl = UrlManager.RequestUrl.baseVideoUrl + getIntent().getStringExtra("videoPath");
        Log.d(mActivity.getClass().getSimpleName(), "播放视频 ------>> url    : " + mUrl);

        // 视频准备完成, 开始播放
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                loadingView.setVisibility(View.GONE);
                ivState.setImageDrawable(getDrawable(R.mipmap.stop));
            }
        });

        // 播放完成
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                loadingView.setVisibility(View.GONE);
                ivState.setImageDrawable(getDrawable(R.mipmap.play));
                String msg = "播放完成";
                //判断视频的总长度与当前长度是否在误差区间内
                if (Math.abs(mVideoView.getDuration() - mVideoView.getCurrentPosition()) > 1000) {
                    msg = "播放错误,可能无网络连接";
                }
                ToastUtils.showShort(msg);
            }
        });

        // 视频未知错误
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                loadingView.setVisibility(View.VISIBLE);
                ivState.setImageDrawable(getDrawable(R.mipmap.play));
                //设置屏幕显示信息
                String msg = "视频未知错误";
                ToastUtils.showShort(msg);
                return false;
            }
        });

        mVideoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                switch (what) {
                    case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                        //开始卡顿
                        loadingView.setVisibility(View.VISIBLE);
                        ivState.setImageDrawable(getDrawable(R.mipmap.stop));
                        break;
                    case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                        //卡顿结束
                        loadingView.setVisibility(View.GONE);
                        ivState.setImageDrawable(getDrawable(R.mipmap.stop));
                        break;
                }
                return true;
            }
        });

        // 本地文件
        // mVideoView.setVideoPath(Environment.getExternalStorageDirectory()+"/dongxiaodong/kk1.mp4");

        // URL形式,支持本地URL和网络URL
        mVideoView.setVideoURI(Uri.parse(mUrl));

        // 设置自带的播放控件
        // mVideoView.setMediaController(new MediaController(this));

        // 开始播放
        mVideoView.start();
        loadingView.setVisibility(View.VISIBLE);
        ivState.setImageDrawable(getDrawable(R.mipmap.stop));
        llManagerLayout.setVisibility(View.GONE);

        mVideoView.getDuration();// 视频的总长度
        mVideoView.getCurrentPosition();    //获取当前播放的位置。

        updateProgress();
    }

    private void updateProgress() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    //延时1秒
                    try {
                        //进入主线程更新UI
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (mVideoView != null) {
                                        if (mVideoView.isPlaying()) {
                                            //获取到视频播放进度
                                            int maxx = mVideoView.getDuration();
                                            int progress = mVideoView.getCurrentPosition();

                                            //设置进度条信息
                                            pbProgress.setMax(maxx);
                                            pbProgress.setProgress(progress);

                                            //得到时间轴字符串
                                            String progressTime = String.format("%02d:%02d", (progress % 3600000) / 60000, (progress % 60000) / 1000);
                                            String maxTime = String.format("%02d:%02d", (maxx % 3600000) / 60000, (maxx % 60000) / 1000);
                                            tvPlayTime.setText(progressTime);
                                            tvTotalTime.setText(maxTime);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        Thread.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }

    @OnClick({R.id.rlRootView, R.id.ivExit, R.id.ivState, R.id.llManagerLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rlRootView:
                toggle();
                break;
            case R.id.ivExit:
                finish();
                break;
            case R.id.ivState:
                if (mVideoView.isPlaying()) {
                    // 暂停
                    mVideoView.pause();
                    ivState.setImageDrawable(getDrawable(R.mipmap.play));
                } else {
                    // 播放
                    mVideoView.start();
                    ivState.setImageDrawable(getDrawable(R.mipmap.stop));
                }
                // 开始播放
                // mVideoView.start();

                // 暂停视频播放
                // mVideoView.pause();

                // 重新播放视频
                // mVideoView.resume();
                // mVideoView.start();
                break;
            case R.id.llManagerLayout:
                // 不能删, 目的: 拦截点击事件
                break;
        }
    }

    private void toggle() {
        if (View.VISIBLE == llManagerLayout.getVisibility()) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        llManagerLayout.setVisibility(View.GONE);
    }

    private void show() {
        llManagerLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mVideoView != null) {
            mVideoView.stopPlayback();
            mVideoView = null;
        }
    }

    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值