Unity中实现VideoPalyer控件操作本地视频

一、搭建基础的视频显示UI(其中时间进度条、音量进度条、及其对应的显示文字UI可以不用搭建)

注意:要想实现鼠标移入显示进度条、音量和时间控件,需要给视频显示控件RawImage添加BoxCollider 2D碰撞体,且调整碰撞体大小为自己想要触发的区域即可。 

二、编写视频控制脚本

/***
*	Title:"可视化" 项目
*		主题:视频播放控制
*	Description:
*		功能:
*		    1、加载本地视频进行播放、暂停、停止
*		    2、获取视频总时长、当前播放时长(对应进度条)
*		    3、实现进度条控制视频音量大小
*		    4、实现鼠标进入显示进度条、音量和时间控件
*		    5、实现鼠标退出隐藏进度条、音量和时间控件
*	Date:2019
*	Version:0.1版本
*	Author:Coffee
*	Modify Recoder:
*/

using Global;
using kernal;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

namespace Control
{
	public class Ctrl_VideosOperation : MonoBehaviour
	{
        #region   视频组件

        #region   基础组件
        //视频播放组件
        private VideoPlayer videoPlayer;                                        //视频组件
        private AudioSource audioSource;                                        //音频组件
        private RawImage rawImage;                                              //显示组件
        public bool satrtplay = false;                                          //开始播放视频开关
        private string videoPath = string.Empty;                                //视频路径

        #endregion

        #region   拓展组件
        //视频控制器
        public Slider m_sliderVideo;
        //音量控制器
        public Slider m_sliderSource;
        //视频总时长
        public Text m_textCount;
        //当前视频时间
        public Text m_textTime;
        //是否拿到视频总时长
        public bool m_isShow;
        //视频是否播放完成
        private bool m_isVideo;
        //时 分的转换
        private int hour, mint;
        private float m_time;
        private float m_timeCount;
        private float m_timeCurrent;

        #endregion

        #endregion

        void Awake()
        {
            //初始化配置
            InitSettings();

        }

        private void Start()
        {
            if (m_sliderSource != null)
            {
                //调节音量方法
                m_sliderSource.onValueChanged.AddListener(delegate { ChangeSource(m_sliderSource.value); });
            }
            
        }

        private void Update()
        {
            if (satrtplay && videoPlayer.isPlaying)
            {
                rawImage.texture = videoPlayer.texture;
                if (m_sliderVideo!=null)
                {
                    //帧数/帧速率=总时长    如果是本地直接赋值的视频,我们可以通过VideoClip.length获取总时长
                    m_sliderVideo.maxValue = (videoPlayer.frameCount / videoPlayer.frameRate);
                    m_time = m_sliderVideo.maxValue;
                    hour = (int)m_time / 60;
                    mint = (int)m_time % 60;
                    m_textCount.text = string.Format("{0:D2}:{1:D2}", hour.ToString(), mint.ToString());
                    //m_isShow = !m_isShow;
                    m_isVideo = false;
                }
                
            }

            if (satrtplay)
            {
                if (m_sliderVideo!=null)
                {
                    if (Mathf.Abs((int)videoPlayer.time - (int)m_sliderVideo.maxValue) == 0)
                    {
                        videoPlayer.frame = (long)videoPlayer.frameCount;
                        videoPlayer.Pause();
                        m_isVideo = true;
                        satrtplay = false;
                        hour = 0;
                        mint = 0;
                        return;
                    }
                    else if (videoPlayer.isPlaying)
                    {
                        m_time = (float)videoPlayer.time;
                        hour = (int)m_time / 60;
                        mint = (int)m_time % 60;
                        m_textTime.text = string.Format("{0:D2}:{1:D2}", hour.ToString(), mint.ToString());
                        m_sliderVideo.value = m_time;
                    }
                }
                
            }

        }


        #region   公有方法

        /// <summary>
        /// 加载封面
        /// </summary>
        public void LoadFirstPicture()
        {
            Play();
            Invoke("Pause", Global_Parameter.INTERVAL_TIME_0DOT2);
        }

        /// <summary>
        /// 获取本地视频
        /// </summary>
        /// <param name="videoPath">视频路径</param>
        /// <returns></returns>
        public bool LoadVideo(string videoPath)
        {
            bool success = false;
            if (!string.IsNullOrWhiteSpace(videoPath))
            {
                //设置视频组件格式
                videoPlayer.source = VideoSource.Url;

                //获取视频
                videoPlayer.url = "file:///" + videoPath;
                this.videoPath = videoPath;
                success = true;

            }
            return success;
        }

        /// <summary>
        /// 播放
        /// </summary>
        /// <returns>false:表示没有指定装载视频(或装载失败)</returns>
        public bool  Play()
        {
            bool success = false;
            if (!string.IsNullOrWhiteSpace(videoPath))
            {
                //设置音效大小
                audioSource.volume = Global_Parameter.INTERVAL_TIME_0DOT5;
                if (m_sliderSource!=null)
                {
                    m_sliderSource.value = audioSource.volume;
                }
                
                videoPlayer.Play();
                success = true;
            }
            return success;
        }
        
        /// <summary>
        /// 暂停
        /// </summary>
        /// <returns>false:表示没有指定装载视频(或装载失败)</returns>
        public bool Pause()
        {
            bool success = false;
            if (!string.IsNullOrWhiteSpace(videoPath))
            {
                videoPlayer.Pause();
                success = true;
            }
            return success;
        }

        
        /// <summary>
        /// 停止
        /// </summary>
        /// <returns>false:表示没有指定装载视频(或装载失败)</returns>
        public bool  Stop()
        {
            bool success = false;
            if (!string.IsNullOrWhiteSpace(videoPath))
            {
                videoPlayer.Stop();
                success = true;
                // 加载封面
                LoadFirstPicture();
            }
            return success;
        }

        /// <summary>
        /// 改变视频进度
        /// </summary>
        /// <param name="value"></param>
        public void ChangeVideo()
        {
            if (videoPlayer.isPrepared)
            {
                videoPlayer.time = m_sliderVideo.value;

                //Debug.Log((long)value);
                //Debug.Log("VideoPlayer Time:" + m_vPlayer.time);
                m_time = (float)videoPlayer.time;
                hour = (int)m_time / 60;
                mint = (int)m_time % 60;
                m_textTime.text = string.Format("{0:D2}:{1:D2}", hour.ToString(), mint.ToString());
            }
            if (m_isVideo == false)
            {
                m_isVideo = true;
            }
        }

        #endregion



        #region   私有方法

        /// <summary>
        /// 初始化配置
        /// </summary>
        private void InitSettings()
        {
            //添加音频、视频组件
            audioSource = this.gameObject.AddComponent<AudioSource>();
            videoPlayer = this.gameObject.AddComponent<VideoPlayer>();
            rawImage = this.gameObject.GetComponent<RawImage>();
            //这3个参数不设置也会没声音 唤醒时就播放关闭
            videoPlayer.playOnAwake = false;
            audioSource.playOnAwake = false;
            audioSource.volume = 0;
            audioSource.Pause();
            
        }

        /// <summary>
        /// 改变音量大小
        /// </summary>
        /// <param name="value"></param>
        private void ChangeSource(float value)
        {
            audioSource.volume = value;
            //text.text = string.Format("{0:0}%", value * 100);
        }

        /// <summary>
        /// 鼠标进入显示视频拓展内容(显示进度条、音量和时间)
        /// </summary>
        private void OnMouseEnter()
        {
            ShowVideoExternInfo(true);
        }

        /// <summary>
        /// 鼠标退出显示视频拓展内容(隐藏进度条、音量和时间)
        /// </summary>
        private void OnMouseExit()
        {
            ShowVideoExternInfo(false);
        }


        //是否显视频的拓展内容(显示进度条、音量和时间)
        private void ShowVideoExternInfo(bool isshow=false)
        {
            if (m_sliderSource != null && m_sliderVideo != null && m_textCount != null && m_textTime != null)
            {
                m_sliderSource.gameObject.SetActive(isshow);
                m_sliderVideo.gameObject.SetActive(isshow);
                m_textCount.gameObject.SetActive(isshow);
                m_textTime.gameObject.SetActive(isshow);
            }
        }

        #endregion



    }//Class_end
}

三、使用方法

 ①将该设备播放控制脚本(Ctrl_VideosOperation.cs)添加给视频显示组件(我这里是:Image_Videos (3))

②新建一个空物体(取名:_TestVideosOperation)作为测试视频操作脚本的挂载物体(Test_VideosOpreation.cs)

③测试视频操作脚本的挂载物体(Test_VideosOpreation.cs)如下:

/***
*	Title:"可视化" 项目
*		主题:测试视频播放控制
*	Description:
*		功能:XXX
*	Date:2019
*	Version:0.1版本
*	Author:Coffee
*	Modify Recoder:
*/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Control;
using System.IO;
using kernal;
using Global;
using UnityEngine.EventSystems;

namespace TestInfo
{
	public class Test_VideosOpreation : MonoBehaviour
    {
        public GameObject showRawImage;                                         //显示面板
        private Ctrl_VideosOperation _VideosOperation;                          //视频控制脚本

       

        void Start()
        {
            if (showRawImage!=null)
            {
                _VideosOperation = showRawImage.GetComponent<Ctrl_VideosOperation>();
            }

            //获得本地的视频路径
            string _VideoPath=@"C:\测试视频\第1章 基本概念清晰版.mp4";

            _VideosOperation.satrtplay = _VideosOperation.LoadVideo(VideoPath);
            _VideosOperation.LoadFirstPicture();

        }


        void Update()
        {
            //开始播放
            if (Input.GetKeyDown(KeyCode.P))
            {
                _VideosOperation.Play();
            }

            //暂停播放
            if (Input.GetKeyDown(KeyCode.L))
            {
                _VideosOperation.Pause();
            }

            //停止播放
            if (Input.GetKeyDown(KeyCode.S))
            {
                _VideosOperation.Stop();
            }

        }

       
    }//Class_end
}

④运行测试,效果图如下:

参考:unity中使用VideoPalyer播放本地视频

猜你喜欢

转载自blog.csdn.net/xiaochenXIHUA/article/details/92029442