Android 使用VideoView实现简单视频播放

2020-09-15  本文已影响0人  嘿_叫我小王

最近项目里要写一个简单的视频播放页面,先上一下效果图吧


image.png

因为考虑我们的需求比较简单,就没有使用三方的框架,采用了原生的VideoView。
因为很长时间没用过原生的VideoView了,大部分采用的都是饺子播放器或者别的三方框架,所以本篇文章主要用于自己复习,技术含量不高(嘿嘿)!

首先是布局文件(资源文件可替换)

<?xml version="1.0" encoding="utf-8"?>
<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:background="@color/black"
    android:orientation="vertical"
    tools:context=".modules.distribution.adapter.LookStudyVedioActivity">

    <com.basetnt.dwxc.commonlibrary.widget.TitleBarView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:paddingBottom="@dimen/dp_10"
        app:title_name=""
        tools:ignore="MissingConstraints" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dp_145">

        <VideoView
            android:id="@+id/videoView"
            android:layout_width="match_parent"
            android:layout_height="211dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/videoView">


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dp_10"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/buttonPlay"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_marginRight="@dimen/dp_5"
                    android:layout_weight="1"
                    android:src="@drawable/vedio_start" />

                <ImageView
                    android:id="@+id/buttonStop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="@dimen/dp_5"
                    android:layout_weight="1"
                    android:src="@drawable/vedio_stop"
                    android:visibility="gone" />

                <TextView
                    android:id="@+id/textViewCurrentPosition"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="00:00"
                    android:textColor="@color/white"
                    android:textSize="@dimen/sp_11" />


                <SeekBar
                    android:id="@+id/seekBar"
                    android:layout_width="250dp"
                    android:layout_height="wrap_content" />

                <TextView
                    android:id="@+id/textViewTime"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="00:00"
                    android:textColor="@color/white"
                    android:textSize="@dimen/sp_11" />
            </LinearLayout>


        </LinearLayout>

        <TextView
            android:id="@+id/textViewStatus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:text="        "
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/videoView" />
    </androidx.constraintlayout.widget.ConstraintLayout>


</LinearLayout>

接下来看代码

public class LookStudyVedioActivity extends BaseMVVMActivity implements View.OnClickListener {
    private VideoView videoView;
    private SeekBar seekBar;
    private ImageView buttonPlay;
    private ImageView buttonStop;
    private TextView textViewTime;
    private TextView textViewCurrentPosition;

    public static void start(Context context) {
        Intent intent = new Intent(context, LookStudyVedioActivity.class);
        context.startActivity(intent);
    }

     //操作进度条
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        public void run() {
            if (videoView.isPlaying()) {
                int current = videoView.getCurrentPosition();
                seekBar.setProgress(current);
                textViewCurrentPosition.setText(time(videoView.getCurrentPosition()));
            }
            handler.postDelayed(runnable, 500);
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_look_study_vedio;
    }

    @Override
    protected void initView() {
        ImmersionBarUtil.BarForWhite(this);
        final Uri uri = Uri.parse("https://视频地址.mp4");
        videoView = (VideoView) this.findViewById(R.id.videoView);
        videoView.setBackground(”封面图资源“);
        videoView.setVideoURI(uri);
        videoView.requestFocus();

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {//播放器准备就绪

            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                textViewTime.setText(time(videoView.getDuration()));
                buttonPlay.setEnabled(true);

            }
        });

        // 在播放完毕被回调
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                textViewCurrentPosition.setText(time(videoView.getDuration()));
                buttonPlay.setVisibility(View.VISIBLE);
                buttonStop.setVisibility(View.GONE);
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                // 发生错误重新播放
//                play();
                Toast.makeText(LookStudyVedioActivity.this, "播放出错", Toast.LENGTH_SHORT).show();
                return false;
            }
        });


        textViewTime = (TextView) findViewById(R.id.textViewTime);
        seekBar = (SeekBar) findViewById(R.id.seekBar);

        // 为进度条添加进度更改事件
        seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);

        textViewCurrentPosition = (TextView) findViewById(R.id.textViewCurrentPosition);

        buttonPlay = (ImageView) findViewById(R.id.buttonPlay);
        buttonPlay.setEnabled(false);
        buttonStop = (ImageView) findViewById(R.id.buttonStop);

        buttonPlay.setOnClickListener(this);
        buttonStop.setOnClickListener(this);

    }


    @Override
    protected void onBindView(Bundle savedInstanceState) {

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.buttonPlay) {
            if (videoView.getBackground() != null) {
                videoView.setBackground(null);
            }
            buttonPlay.setVisibility(View.GONE);
            buttonStop.setVisibility(View.VISIBLE);
            // 开始线程,更新进度条的刻度
            handler.postDelayed(runnable, 0);
            videoView.start();
            seekBar.setMax(videoView.getDuration());
        } else if (id == R.id.buttonStop) {
            buttonPlay.setVisibility(View.VISIBLE);
            buttonStop.setVisibility(View.GONE);
            if (videoView.isPlaying()) {
                videoView.pause();
            }
        }
    }

    private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        // 当进度条停止修改的时候触发
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (videoView.isPlaying()) {
                // 设置当前播放的位置
                videoView.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {

        }
    };

//    protected void play() {
//
//        if (buttonPlay.getText().equals("播放")) {
//            buttonPlay.setText("暂停");
//            textViewStatus.setText("请您欣赏");
//            // 开始线程,更新进度条的刻度
//            handler.postDelayed(runnable, 0);
//            videoView.start();
//            seekBar.setMax(videoView.getDuration());
//
//        } else {
//            buttonPlay.setText("播放");
//            if (videoView.isPlaying()) {
//                videoView.pause();
//            }
//        }
//
//    }

//    视频停止
//    protected void stop() {
//        if (videoView.isPlaying()) {
//            videoView.stopPlayback();
//        }
//    }

    protected String time(long millionSeconds) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(millionSeconds);
        return simpleDateFormat.format(c.getTime());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }
}

上一篇下一篇

猜你喜欢

热点阅读