关于使用VideoView播放视频

本文介绍了一种使用Android VideoView实现网络视频播放的方法,包括自定义控制条与VideoView的关联,以及如何处理竖屏与横屏切换的问题。文中详细展示了Activity代码与布局文件配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于使用VideoView播放视频

刚好项目中需要一个简单播放网络视频的功能,在网上看了一些感觉不是很满意就自己写了一个,主要是自定义控制条和VideoView的关联以及竖屏和横屏的切换。


  • 配置清单

权限

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

activity属性配置

android:configChanges="keyboardHidden|orientation|screenSize"
  • 布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.fsp.zp.testforvideo.MainActivity">

  <FrameLayout
      android:id="@+id/frameLayout"
      android:layout_width="match_parent"
      android:layout_height="200dp">
      <com.fsp.zp.testforvideo.MyVideoView
          android:id="@+id/videoView"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />
    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone"
        style="@android:style/Widget.Material.ProgressBar.Small"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:gravity="center_vertical">
      <ImageView
          android:id="@+id/iv1"
          android:layout_width="25dp"
          android:layout_height="25dp"
          android:src="@drawable/start"
          android:layout_marginLeft="5dp"/>
      <TextView
          android:id="@+id/nowTime"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="0:00"
          android:textColor="#fff"/>
      <SeekBar
          android:id="@+id/seekbar"
          android:layout_width="0dp"
          android:layout_height="wrap_content"
          android:layout_weight="1"
          android:thumbOffset="0dp"/>
      <TextView
          android:id="@+id/allTime"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#fff"
          android:text=""
          android:layout_marginRight="5dp"/>
      <ImageView
          android:id="@+id/full"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:src="@drawable/full"
          android:layout_marginRight="5dp"/>
    </LinearLayout>
  </FrameLayout
     >
  • Avtivity代码
package com.fsp.zp.testforvideo;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnInfoListener {


    private MyVideoView videoView;
    private ImageView startAndPause;
    private TextView nowTime;
    private SeekBar seekBar;
    private TextView allTime;
    private ImageView full;

    Timer timer = new Timer();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            nowTime.setText(getFormatTime(videoView.getCurrentPosition())
            );
        }
    };
    private FrameLayout frameLayout;
    private ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videoView = (MyVideoView) this.findViewById(R.id.videoView);
        Uri uri = Uri.parse("http://112.253.22.157/17/z/z/y/u/zzyuasjwufnqerzvyxgkuigrkcatxr/hc.yinyuetai.com/D046015255134077DDB3ACA0D7E68D45.flv");
        videoView.setVideoURI(uri);
        startAndPause = ((ImageView) findViewById(R.id.iv1));
        nowTime = ((TextView) findViewById(R.id.nowTime));
        seekBar = ((SeekBar) findViewById(R.id.seekbar));
        allTime = ((TextView) findViewById(R.id.allTime));
        full = ((ImageView) findViewById(R.id.full));
        startAndPause.setOnClickListener(this);
        frameLayout = ((FrameLayout) findViewById(R.id.frameLayout));
        progressbar = ((ProgressBar) findViewById(R.id.progressbar));
        videoView.setOnCompletionListener(this);
        videoView.setOnInfoListener(this);
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                progressbar.setVisibility(View.GONE);//缓冲完成就隐藏
                seekBar.setMax(videoView.getDuration());

                String time = getFormatTime(videoView.getCurrentPosition());
                nowTime.setText(time);
                String time1 = getFormatTime(videoView.getDuration());
                allTime.setText(time1);
                seekBar.setProgress(1);
                videoView.seekTo(1);
                mp.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                    @Override
                    public void onBufferingUpdate(MediaPlayer mp, int percent) {

                    }
                });
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                videoView.seekTo(seekBar.getProgress());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                if (videoView != null && videoView.isPlaying()) {
                    videoView.seekTo(progress);
                }
            }
        });
        full.setOnClickListener(this);
    }

    //是否使用Timer定时器
    boolean isNeed = true;

    //是否显示progressbar
    boolean isShowProgessBar = false;

    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.iv1:
                if (videoView.isPlaying()) {
                    videoView.pause();
                    isShowProgessBar = false;
                    startAndPause.setImageResource(R.drawable.start);
                } else {
                    videoView.start();
                    isShowProgessBar = true;
                    startAndPause.setImageResource(R.drawable.pause);

                    isNeed = false;
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            handler.sendEmptyMessage(0);
                        }
                    }, 0, 500);

                }
                break;
            case R.id.full:
                if (isScreenOriatationPortrait(MainActivity.this)) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 设置当前activity为横屏
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    frameLayout.setLayoutParams(layoutParams);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 设置当前activity为竖屏
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(MainActivity.this, 200));
                    frameLayout.setLayoutParams(layoutParams);
                }

                break;
        }
    }

    private String getFormatTime(int time){
        final SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        String hms = formatter.format(time);
        return hms;
    }


    /**
     * dip to px
     */
    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 返回当前屏幕是否为竖屏。
     *
     * @param context
     * @return 当且仅当当前屏幕为竖屏时返回true, 否则返回false。
     */
    public static boolean isScreenOriatationPortrait(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        isShowProgessBar = false;

        progressbar.setVisibility(View.GONE);

        videoView.seekTo(0);
        seekBar.setProgress(0);
        startAndPause.setImageResource(R.drawable.start);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START && isShowProgessBar) {
            progressbar.setVisibility(View.VISIBLE);
        } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
            progressbar.setVisibility(View.GONE);
        }
        return true;
    }


}

到此代码上基本完成了 横竖屏的切换是在横屏时把不需要的控件直接Gone掉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值