美文网首页Android开发
android开发之简单视频播放器(VideoView)

android开发之简单视频播放器(VideoView)

作者: zzj丶 | 来源:发表于2017-02-15 17:38 被阅读6664次

简单视频播放器的使用
一、简单使用videoView和MediaController实现播放控制
1、添加需要的权限

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

2、设置布局

 <VideoView
            android:id="@+id/main_video"
            android:layout_width="match_parent"
            android:layout_height="240dp"
            />

3、实例化VideoView

VideoView  videoView = (VideoView) findViewById(R.id.main_video);
      MediaController  controller = new MediaController(this);//实例化控制器
//        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"jiaoxue.mp4";
        /**
         * 本地播放
         */
//        videoView.setVideoPath("path");
        /**
         * 网络播放
         */
        videoView.setVideoURI(Uri.parse("http://192.168.1.109:8080/video/jiaoxue.mp4"));

        /**
         * 将控制器和播放器进行互相关联
         */
        controller.setMediaPlayer(videoView);
        videoView.setMediaController(controller);

二、自定义播放器 (贴上源码)

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.zzj.myeasyvideoplaydemo.MainActivity">

    <RelativeLayout

        android:layout_width="match_parent"
        android:layout_height="240dp">
        <VideoView
            android:id="@+id/main_video"
            android:layout_width="match_parent"
            android:layout_height="240dp"
            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:orientation="vertical"
            android:layout_alignParentBottom="true"
            >
            <SeekBar
                android:layout_width="match_parent"
                android:layout_height="5dp"
                android:layout_marginLeft="-20dp"
                android:layout_marginRight="-20dp"
                android:max="100"
                android:indeterminate="false"
                android:progress="20"
                />
            <RelativeLayout
                android:gravity="center_vertical"
                android:background="#101010"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    >
                    <ImageView
                        android:id="@+id/play_pasue_image"
                        android:layout_marginLeft="5dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@mipmap/video_play_blue"
                        />
                    <TextView
                        android:id="@+id/main_current_time"
                        android:layout_marginLeft="16dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="00:00:00"
                        android:textSize="14dp"
                        android:textColor="#ffffff"
                        />
                    <TextView
                        android:layout_marginLeft="5dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="/"
                        android:textSize="14dp"
                        android:textColor="#4c4c4c"
                        />
                    <TextView
                        android:id="@+id/main_totally_time"
                        android:layout_marginLeft="5dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="00:00:00"
                        android:textSize="14dp"
                        android:textColor="#ffffff"
                        />
                </LinearLayout>
                <LinearLayout
                    android:layout_marginRight="5dp"
                    android:layout_alignParentRight="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@mipmap/video_sound_switch"
                        />
                    <SeekBar
                        android:layout_width="100dp"
                        android:layout_height="5dp"
                        android:progress="20"
                        android:max="100"
                        />
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@mipmap/play"
                        />
                </LinearLayout>
            </RelativeLayout>
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

视频Java类:

public class TestMovieActivity extends BaseActivity {
    public static final int UPDATA_VIDEO_NUM = 1;
    private CustomVideoView videoView;
    private MediaController controller;//控制器
    private RelativeLayout videoLayout;
    private LinearLayout controllerLayout;//播放器的总控制布局
    private SeekBar play_seek, volume_seek;//播放进度和音量控制进度
    private ImageView play_controller_image, screen_image,volume_Image;
    private TextView current_time_tv, totally_time_tv;
    private String path;
    private int screen_width, screen_height;
    private AudioManager audioManager;//音量控制器
    private boolean screen_flag = true;//判断屏幕转向

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //实例化音量控制器
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        setContentView(R.layout.act_testmovie);

        initView();
        initData();
        initViewOnClick();
//        controller = new MediaController(this);//实例化控制器
//        path = Environment.getExternalStorageDirectory().getAbsolutePath()+"jiaoxue.mp4";
        /**
         * 本地播放
         */
//        videoView.setVideoPath("");
        /**
         * 网络播放
         */
        videoView.setVideoURI(Uri.parse("http://192.168.1.109:8080/video/jiaoxue.mp4"));
        //视频播放时开始刷新
//        videoView.start();
        play_controller_image.setImageResource(R.mipmap.video_play_blue);
//        handler.sendEmptyMessage(UPDATA_VIDEO_NUM);
        /**
         * 将控制器和播放器进行互相关联
         */
//        controller.setMediaPlayer(videoView);
//        videoView.setMediaController(controller);
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeMessages(UPDATA_VIDEO_NUM);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(UPDATA_VIDEO_NUM);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 判断当前屏幕的横竖屏状态
        int screenOritentation = getResources().getConfiguration().orientation;
        if (screenOritentation == Configuration.ORIENTATION_LANDSCAPE) {
            //横屏时处理
            setVideoScreenSize(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            volume_seek.setVisibility(View.VISIBLE);
            volume_Image.setVisibility(View.VISIBLE);
            screen_flag = false;
            //清除全屏标记,重新添加
            getWindow().clearFlags((WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN));
            getWindow().addFlags((WindowManager.LayoutParams.FLAG_FULLSCREEN));
        } else {
            //竖屏时处理
            setVideoScreenSize(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtils.dp2px(mContext,240));
            screen_flag = true;
            volume_seek.setVisibility(View.GONE);
            volume_Image.setVisibility(View.GONE);
            //清除全屏标记,重新添加
            getWindow().clearFlags((WindowManager.LayoutParams.FLAG_FULLSCREEN));
            getWindow().addFlags((WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN));
        }
    }

    /**
     * 通过handler对播放进度和时间进行更新
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == UPDATA_VIDEO_NUM) {
                //获取视频播放的当前时间
                int currentTime = videoView.getCurrentPosition();
                //获取视频的总时间
                int totally = videoView.getDuration();
                //格式化显示时间
                updataTimeFormat(totally_time_tv, totally);
                updataTimeFormat(current_time_tv, currentTime);
                //设置播放进度
                play_seek.setMax(totally);
                play_seek.setProgress(currentTime);
                //自己通知自己更新
                handler.sendEmptyMessageDelayed(UPDATA_VIDEO_NUM, 500);//500毫秒刷新
            }
        }
    };

    /**
     * 设置横竖屏时的视频大小
     *
     * @param width
     * @param height
     */
    private void setVideoScreenSize(int width, int height) {
        //获取视频控件的布局参数
        ViewGroup.LayoutParams videoViewLayoutParams = videoView.getLayoutParams();
        //设置视频范围
        videoViewLayoutParams.width = width;
        videoViewLayoutParams.height = height;
        videoView.setLayoutParams(videoViewLayoutParams);
        //设置视频和控制组件的layout
        ViewGroup.LayoutParams videoLayoutLayoutParams= videoLayout.getLayoutParams();
        videoLayoutLayoutParams.width = width;
        videoLayoutLayoutParams.height = height;
        videoLayout.setLayoutParams(videoLayoutLayoutParams);
    }

    /**
     * 时间格式化
     *
     * @param textView    时间控件
     * @param millisecond 总时间 毫秒
     */
    private void updataTimeFormat(TextView textView, int millisecond) {
        //将毫秒转换为秒
        int second = millisecond / 1000;
        //计算小时
        int hh = second / 3600;
        //计算分钟
        int mm = second % 3600 / 60;
        //计算秒
        int ss = second % 60;
        //判断时间单位的位数
        String str = null;
        if (hh != 0) {//表示时间单位为三位
            str = String.format("%02d:%02d:%02d", hh, mm, ss);
        } else {
            str = String.format("%02d:%02d", mm, ss);
        }
        //将时间赋值给控件
        textView.setText(str);
    }

    /**
     * 按钮点击事件
     */
    private void initViewOnClick() {
        //播放按钮事件
        play_controller_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断播放按钮的状态
                if (videoView.isPlaying()) {
                    play_controller_image.setImageResource(R.mipmap.video_play_blue);
                    //视频暂停
                    videoView.pause();
                    //当视频处于暂停状态,停止handler的刷新
                    handler.removeMessages(UPDATA_VIDEO_NUM);
                } else {
                    play_controller_image.setImageResource(R.mipmap.video_pause_white);
                    videoView.start();
                    //当视频播放时,通知刷新
                    handler.sendEmptyMessage(UPDATA_VIDEO_NUM);
                }
            }
        });
        //播放进度条事件
        play_seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //设置当前的播放时间
                updataTimeFormat(current_time_tv, progress);
                if (videoView.getDuration() == progress) {
                    play_controller_image.setImageResource(R.mipmap.video_play_blue);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //拖动视频进度时,停止刷新
                handler.removeMessages(UPDATA_VIDEO_NUM);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //停止拖动后,获取总进度
                int totall = seekBar.getProgress();
                //设置VideoView的播放进度
                videoView.seekTo(totall);
                //重新handler刷新
                handler.sendEmptyMessage(UPDATA_VIDEO_NUM);

            }
        });
        //音量控制条事件
        volume_seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //设置音量变动后系统的值
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //设置全屏按钮点击事件
        screen_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLog("------当前屏幕标记----:"+screen_flag);
                if(screen_flag){
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//控制屏幕竖屏
                }else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//控制屏幕横屏
                }
            }
        });
    }

    @Override
    protected void initView() {
        videoView = (CustomVideoView) findViewById(R.id.main_video);
        videoLayout = (RelativeLayout) findViewById(R.id.act_testmovie_videolayout);
        controllerLayout = (LinearLayout) findViewById(R.id.main_controller_liner);
        play_seek = (SeekBar) findViewById(R.id.main_play_seek);
        volume_seek = (SeekBar) findViewById(R.id.main_volume_seek);
        current_time_tv = (TextView) findViewById(R.id.main_current_time);
        totally_time_tv = (TextView) findViewById(R.id.main_totally_time);
        play_controller_image = (ImageView) findViewById(R.id.play_pasue_image);
        screen_image = (ImageView) findViewById(R.id.main_screen_image);
        volume_Image = (ImageView) findViewById(R.id.act_testmovies_volume_image);
        DisplayMetrics metric = new DisplayMetrics();
        screen_width = metric.widthPixels;
        screen_height = metric.heightPixels;
    }

    @Override
    protected void initData() {
        //获取设置音量的最大值
        int volumeMax = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        volume_seek.setMax(volumeMax);
        //获取设置当前音量
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        volume_seek.setProgress(currentVolume);
    }
}

补上CustomVideoView

public class CustomVideoView extends VideoView {
    //声明屏幕的大小
    int width = 1920;
    int height = 1080;
    public CustomVideoView(Context context) {
        super(context);
    }

    public CustomVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public CustomVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //设置宽高
        int defaultWidth = getDefaultSize(width,widthMeasureSpec);
        int defaultHeight = getDefaultSize(height,heightMeasureSpec);
        setMeasuredDimension(defaultWidth,defaultHeight);
    }
}

相关文章

网友评论

  • 举头望明月泣:gayhub没有源码上传吗,发现不能全屏和资源不能播放
  • fbf85b8162cc:请问有源码吗?
  • eb5bced3d042:没有这个类啊CustomVideoView
    LXJDBXJ:@枫叶_1541 那是自定义的
    zzj丶:这是以前学习的时候做的记录,代码贴出来 ,希望对你有用
  • burro630:楼主 我想问问CustomVideoView这个类呢。咋不贴出来、、
  • 叶为正:请问有源码吗
    叶为正:@zzj丶 好的,谢谢
    zzj丶:你把最后布局和代码 复制下就可以了

本文标题:android开发之简单视频播放器(VideoView)

本文链接:https://www.haomeiwen.com/subject/edwqwttx.html