[Unity] unity videoplayer组件播放视频源码

查看:750 |回复:2 | 2022-4-6 14:49:00

您需要 登录 才可以下载或查看,没有账号?注册

x
本帖最后由 LotusMyth 于 2022-4-6 15:02 编辑


using System;
using System.Collections;
using System.Collections.Generic;
using UIFORM;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

public class VideoPlayPanel : MonoBehaviour
{
    public string playName = "极乐净土";
    public string format = ".mp4";
    //正在播的视频
    public VideoClip vc_Video;
    private Button Btu_Close;
    //需要添加播放器的物体
    private Transform go_Screen;
    //图像
    private RawImage ri_Screen;
    //播放器
    private VideoPlayer vPlayer;
    //音频组件
    private AudioSource source;
    private Transform downParent;
    //视频控制器
    private Slider sliderVideo;
    //视频名称
    private Text text_VideoName;
    //播放
    private Button btn_Play;
    //声音
    private Button btn_Sound;
    //全屏
    private Button btn_Scene;

    //音量控制器
    private Slider sliderSource;
    //音量大小
    private Text text_Sound;
    //当前视频时间
    private Text text_currTime;
    //视频总时长
    private Text text_totalCount;

    private float playSpeed = 1;//视频播放速度
    //是否拿到视频总时长
    private bool isShow;
    //前进后退的大小
    private float numBer = 20f;
    //时 分的转换
    private int hour, minute, second;
    private float totalTime;
    private float time_Count;
    private float time_Current;
    //视频是否播放完成
    private bool isVideoEnd;
    //视频是否正在播放 播放中的暂停与播放
    private bool isPlay = true;
    private bool isSound = true;
    private bool isScene = true;

    private bool _SliderVideoDowing = false;
    //是否关闭面板
    public bool isClosePanel = true;
    // Use this for initialization
    //是否发送完成事件
    private bool isEndInit = false;
    //第一次打开
    private bool isOneOpen = false;
  
    private void Awake()
    {
        Btu_Close = transform.Find("Button_Close").GetComponent<Button>();
        go_Screen = transform.Find("bg/Screen");
        downParent = transform.Find("bg/DowmParent");

        ri_Screen = go_Screen.GetComponent<RawImage>();
        vPlayer = go_Screen.GetComponent<VideoPlayer>();
        source = go_Screen.GetComponent<AudioSource>();
        sliderVideo = downParent.Find("Slider_Play").GetComponent<Slider>();
        text_VideoName = downParent.Find("VideoName").GetComponent<Text>();
        btn_Play = downParent.Find("Btu_Play").GetComponent<Button>();
        btn_Sound = downParent.Find("Btu_Audio").GetComponent<Button>();
        btn_Scene = downParent.Find("Btu_MaxScene").GetComponent<Button>();
        sliderSource= downParent.Find("Slider_Audio").GetComponent<Slider>();
        text_Sound = downParent.Find("Txt_Sound").GetComponent<Text>();
        text_currTime = downParent.Find("Times/CurrentTime").GetComponent<Text>();
        text_totalCount = downParent.Find("Times/TotalTime").GetComponent<Text>();
    }
    protected  void Start()
    {
        //这3个参数不设置也会没声音 唤醒时就播放关闭
        vPlayer.playOnAwake = false;
        source.playOnAwake = false;
        source.Pause();

        //播放Resources下的视频
        LoadResourcesVideo();

        btn_Play.onClick.AddListener(delegate { OnClick(0); });
        btn_Sound.onClick.AddListener(delegate { OnClick(1); });
        btn_Scene.onClick.AddListener(delegate { OnClick(2); });

        sliderSource.value = source.volume;
        text_Sound.text = string.Format("{0:0}%", source.volume * 100);
        sliderSource.onValueChanged.AddListener(delegate { ChangeSource(sliderSource.value); });


        EventTriggerListener.Get(sliderVideo.gameObject).onDown = _SliderVideoDown;
        EventTriggerListener.Get(sliderVideo.gameObject).onUp = _SliderVideoUp;

        Btu_Close.onClick.AddListener(() =>
        {
            if (isClosePanel)
            {
                //OnExit();
                isEndInit = false;
                OnPlayPause();
               
                vPlayer.time = 0;
                time_Count = 0;
                time_Current = 0;
                sliderVideo.value = 0;
                btn_Play.GetComponent<Image>().sprite = LoadSprite("ButtonUI/" + "pause");
                //显示视频播放时间时间
                OnShowCurrentTime((float)vPlayer.time);
            }

        });
    }
    void Update()
    {
        if (isEndInit)
        {
            if (vPlayer.isPlaying && isShow)
            {
                //把图像赋给RawImage
                ri_Screen.texture = vPlayer.texture;
                //帧数/帧速率=总时长    如果是本地直接赋值的视频,我们可以通过VideoClip.length获取总时长
                sliderVideo.maxValue = vPlayer.frameCount / vPlayer.frameRate;

                totalTime = sliderVideo.maxValue;
                hour = (int)totalTime / 3600;
                minute = (int)totalTime % 3600 / 60;
                second = (int)totalTime % 3600 % 60;
                text_totalCount.text = string.Format("{0:D2}:{1:D2}:{2:D2}", hour.ToString(), minute.ToString(), second.ToString());

                isShow = !isShow;
            }
            if (Mathf.Abs((int)vPlayer.time - (int)sliderVideo.maxValue) == 0 && isVideoEnd)
            {
                vPlayer.frame = (long)vPlayer.frameCount;
                //vPlayer.Stop();
                isVideoEnd = false;
                isShow = true;
                //显示视频播放时间时间
                OnShowCurrentTime(totalTime);
                sliderVideo.value = totalTime;
                //暂停
                OnPlayPause();
                Debug.Log("播放完成!");

            }
            if (_SliderVideoDowing)
            {
                vPlayer.time = sliderVideo.value;
                //显示视频播放时间时间
                OnShowCurrentTime((float)vPlayer.time);
            }

            if (isVideoEnd && vPlayer.isPlaying)
            {
                time_Count += Time.deltaTime;
                sliderVideo.value = (float)vPlayer.time;
                if ((time_Count - time_Current) >= 0.5f && !_SliderVideoDowing)
                {
                    time_Count = 0;//

                    //显示视频播放时间时间
                    OnShowCurrentTime((float)vPlayer.time);
                }
            }
        }
    }
    //加载视频
    public void LoadResourcesVideo(string videoName)
    {
        //StopSound();
        //停止所有的协程
        StopAllCoroutines();
        playName = null;
        playName = videoName;
        LoadResourcesVideo();
        text_VideoName.text = videoName;
    }
    /// <summary>
    ///     初始化VideoPlayer
    /// </summary>
    /// <param name="url"></param>
    private void LoadStreamingAssetsVideo()
    {
        //设置为URL模式
        vPlayer.source = VideoSource.Url;
        //设置播放路径
        vPlayer.url = Application.dataPath + "/StreamingAssets/Video/" + playName + format;
        LoadAudio();
    }
    public void LoadResourcesVideo()
    {
        //设置为URL模式
        vPlayer.source = VideoSource.VideoClip;
        //VideoPlayer加载视频
        string url = "FuncPrefab/VideoPlayPanel/Video/" + playName;
        vc_Video = Resources.Load<VideoClip>(url);
        if (vc_Video == null)
        {
            Debug.LogError("找不到视频路径:" + url);
            return;
        }
        vPlayer.clip = null;
        vPlayer.clip = vc_Video;
        text_VideoName.text = playName;
        LoadAudio();
    }
    //设置音频组件 播放视频
    public void LoadAudio()
    {
        isVideoEnd = true;
        isShow = true;
        vPlayer.time = 0;
        time_Count = 0;
        time_Current = 0;
        sliderVideo.value = 0;
        //在视频中嵌入的音频类型
        vPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
        vPlayer.controlledAudioTrackCount = 1;
        //把声音组件赋值给VideoPlayer
        vPlayer.SetTargetAudioSource(0, source);

        //当VideoPlayer全部设置好的时候调用
        vPlayer.prepareCompleted += Prepared;
        //启动播放器
        vPlayer.Prepare();
        vPlayer.playbackSpeed = playSpeed;

        btn_Play.GetComponent<Image>().sprite = LoadSprite("ButtonUI/" + "pause");
        //显示视频播放时间时间
        OnShowCurrentTime((float)vPlayer.time);
        //OnEnter();
        isEndInit = true;
        isPlay = true;

        isOneOpen = true;
    }

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

    /// <summary>
    ///     改变视频进度
    /// </summary>
    /// <param name="value"></param>
    public void ChangeVideo(float value)
    {
        if (vPlayer.isPrepared)
        {
            vPlayer.time = (long)value;
            Debug.Log("VideoPlayer Time:" + vPlayer.time);
            //显示视频播放时间时间
            OnShowCurrentTime((float)vPlayer.time);
        }
    }

    private void OnClick(int num)
    {
        switch (num)
        {
            case 0:
                if (isPlay)//暂停
                {
                    OnPlayPause();
                }
                else//播放
                {

                    if (sliderVideo.value == totalTime)
                    {
                        OnShowCurrentTime(0);
                        sliderVideo.value = 0;
                        vPlayer.time = 0;
                    }
                    vPlayer.Play();
                    isEndInit = true;
                    isVideoEnd = true;
                    isPlay = true;
                    Time.timeScale = 1;
                    btn_Play.GetComponent<Image>().sprite = LoadSprite("ButtonUI/" + "pause");

                }
                break;
            case 1:
                if (isSound)
                {
                    isSound = false;
                    source.mute = true;
                    btn_Sound.GetComponent<Image>().sprite = LoadSprite("ButtonUI/" + "OpenSound");
                }
                else
                {
                    isSound = true;
                    source.mute = false;
                    btn_Sound.GetComponent<Image>().sprite = LoadSprite("ButtonUI/" + "closeSound");
                }
                break;
            case 2:
                if (isScene)
                {
                    isScene = false;
                    //设置背景Plane的大小
                    go_Screen.GetComponent<RectTransform>().sizeDelta = new Vector2(1920, 1080);
                }
                else
                {
                    isScene = true;
                }
                break;

            default:
                break;
        }
    }
    // Update is called once per frame

    private void _SliderVideoDown(GameObject go)
    {
        if (vPlayer != null && vPlayer.isPrepared)
        {
            time_Count = 0;//
            _SliderVideoDowing = true;
            //显示视频播放时间时间
            OnShowCurrentTime((float)vPlayer.time);
            vPlayer.time = sliderVideo.value;
            Debug.Log("Value: " + sliderVideo.value + "   " + vPlayer.time);
            if (isPlay)
            {
                //暂停
                vPlayer.Pause();
            }
        }
    }
    private void _SliderVideoUp(GameObject go)
    {
        if (vPlayer != null && vPlayer.isPrepared)
        {
            _SliderVideoDowing = false;
            if (isPlay && isVideoEnd)
            {
                //暂停
                vPlayer.Play();
            }
        }
    }
    void Prepared(VideoPlayer player)
    {
        player.Play();
    }


    //暂停
    public void OnPlayPause()
    {
        isPlay = false;
        vPlayer.Pause();
        //Time.timeScale = 0;
        btn_Play.GetComponent<Image>().sprite = LoadSprite("ButtonUI/" + "play");
    }
    //显示视频播放时间时间
    private void OnShowCurrentTime(float pTime)
    {
        hour = (int)pTime / 3600;
        minute = (int)pTime % 3600 / 60;
        second = (int)pTime % 3600 % 60;
        text_currTime.text = string.Format("{0:D2}:{1:D2}:{2:D2}", hour.ToString(), minute.ToString(), second.ToString());
    }
    //视频播放完成
    public void OnPlayEnd()
    {
        isClosePanel = true;
    }
    //第二次打开
    public void TowPlayer()
    {

        vPlayer.Play();
        isEndInit = true;
        isVideoEnd = true;
        isPlay = true;
    }

    /// <summary>
    /// 加载一个Sprite
    /// </summary>
    /// <param name="assetName">资源名称</param>
    public Sprite LoadSprite(string assetName)
    {
        Texture texture = (Texture)Resources.Load("FuncPrefab/VideoPlayPanel/ItemUI/" + assetName);

        Sprite sprite = Sprite.Create((Texture2D)texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
        return sprite;
    }
}

2022-4-6 14:49:00  
 赞 赞 0

使用道具 登录

2个回答,把该问题分享到群,邀请大神一起回答。
2#
不错,支持下 感谢分享!
回复 收起回复
2024-10-30 01:36:11   回复
 赞 赞 0

使用道具 登录

CG 游戏行业专业问题

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表