Unity video playback

Unity video playback

foreword

There are many ways to play video in the Unity engine, here are two. One is to use the texture of the RawImage component to play the video, and copy the picture of each frame of the video to the texture map of the RawImage to realize the playback and display of the video; the other is to use the plug-in Av Pro to play the video. In this In the case, I used the AVProVideo1.9.6 version of the plug-in (the plug-in is placed at the end of the article, please pick it up if you need it).

Two ways to play video in Unity

(1) Use RawImage to play video
First create a RawImage, adjust it to the video resolution (1920*1080 in this case), and mount the VideoPlayer component on the RawImage (this step can also be automatically mounted by code, you can choose by yourself ), as shown in the figure below:
insert image description here
In order to meet the actual project needs, the video is read from an external file to make the operation of replacing the video smoother, and the video resource path option of VideoPlayer is changed to URL to grab the video file. Next, use the
insert image description here
script To operate, you can read the video from the external folder and play the video. The script is as follows:

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

public class VideoPlayerController : MonoBehaviour
{
    
    
    RawImage videopanel;
    VideoPlayer player;
    public string videoname;//自行在外部填写

    bool isplay;

    // Start is called before the first frame update
    void Start()
    {
    
    
        videopanel = transform.GetComponent<RawImage>();
        player = transform.GetComponent<VideoPlayer>();
        isplay = false;
    }

    KeyCode code;

    // Update is called once per frame
    void Update()
    {
    
    
        VideoPlayStatus();
        if (isplay)
        {
    
    
            videopanel.texture = player.texture;
        }
    }

    /// <summary>
    /// 控制视频的播放状态
    /// </summary>
    void VideoPlayStatus()
    {
    
    
        if (Input.GetKeyDown(KeyCode.Return))
        {
    
    
            GetVideoUrl(videoname);
            isplay = true;
            Debug.Log("获取视频并播放");
        }
        if (!isplay)
        {
    
    
            if (Input.GetKeyDown(KeyCode.Space))
            {
    
    
                isplay = true;
                player.Play();
                Debug.Log("继续播放视频");
            }
        }
        else
        {
    
    
            if (Input.GetKeyDown(KeyCode.Space))
            {
    
    
                isplay = false;
                player.Pause();
                Debug.Log("暂停");
            }
        }
        if (Input.GetKeyDown(KeyCode.Escape))
        {
    
    
            player.Stop();
            Debug.Log("停止");
        }
    }

    /// <summary>
    /// 获取视频资源(可更改参数进行切换视频操作)
    /// </summary>
    void GetVideoUrl(string name)
    {
    
    
        name = videoname;
        string path = Application.streamingAssetsPath + "/" + name;
        GetVideoPlayCommponent();
        if (File.Exists(path))
        {
    
    
            player.url = path;
        }
        else
        {
    
    
            Debug.LogError("视频不存在");
        }
    }

    /// <summary>
    /// 选择是否手动挂载VideoPlayer组件
    /// </summary>
    void GetVideoPlayCommponent()
    {
    
    
        if (!transform.GetComponent<VideoPlayer>())
        {
    
    
            player=transform.gameObject.AddComponent<VideoPlayer>();
        }
        else
        {
    
    
            return;
        }
    }
}

The demonstration effect is as follows:
insert image description here

(2) Use the plug-in Av Pro to play video
First import the plug-in and create AVpro Video uGUI, as shown in the figure below:
insert image description here
Adjust the AVpro Video uGUI to the required video resolution size, and uncheck the video default basemap as required, and set the Scale Mode Change the mode to full screen (especially important when doing video switching)
insert image description here

Create MediaPlayer, as shown in the figure below:
insert image description here
Assign MediaPlayer to AVpro Video uGUI, you can directly click the Browse button of MediaPlayer to select the video, in order to facilitate the actual project needs, read the video usage parameters, as shown in the figure below:
insert image description here

Use scripts to perform various controls on the video, complete a relatively complete control of video playback (including no time to switch videos), write the play, pause, and stop methods and call them directly, use the following script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using RenderHeads.Media.AVProVideo;

public class VideoController : MonoBehaviour
{
    
    
    public Slider slider;
    MediaPlayer media;
    //视频播放时间
    public Text play_time;
    int play_m;
    int play_s;
    int m;
    int s;

    bool isplay = true;
    bool _wasPlayingOnScrub;
    float _setVideoSeekSliderValue;

    public MediaPlayer.FileLocation _location = MediaPlayer.FileLocation.RelativeToStreamingAssetsFolder;
    DisplayUGUI uGUI;
    string videoname0;
    string videoname1;
    public Texture[] tex; //切换视频时需要先切换视频的首帧图片 不然会泛白

    private void Start()
    {
    
    
        slider.value = 0;
        media = GameObject.Find("MediaPlayer").GetComponent<MediaPlayer>();
        uGUI = transform.GetComponent<DisplayUGUI>();
        videoname0 = "SampleCube.mp4";
        videoname1 = "SampleSphere.mp4";
    }
    public void OnVideoSliderDown()
    {
    
    
        if (media)
        {
    
    
            _wasPlayingOnScrub = media.Control.IsPlaying();
            if (_wasPlayingOnScrub)
            {
    
    
                media.Control.Pause();
            }
            OnVideoSeekSlider();
        }
    }
    public void OnVideoSliderUp()
    {
    
    
        if (media && _wasPlayingOnScrub)
        {
    
    
            media.Control.Play();
            _wasPlayingOnScrub = false;
        }
    }


    void Update()
    {
    
    
        VideoPlay_time();
        VideoTimeSlider();
        Controller();
    }


    void Controller()
    {
    
    
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
    
    
            uGUI._defaultTexture = tex[0];
            OnOpenVideoFile(videoname0);
        }
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
    
    
            uGUI._defaultTexture = tex[1];
            OnOpenVideoFile(videoname1);
        }
    }

    /// <summary>
    /// 视频进度条更新
    /// </summary>
    void VideoTimeSlider()
    {
    
    
        if (media && media.Info != null && media.Info.GetDurationMs() > 0f)
        {
    
    
            float time = media.Control.GetCurrentTimeMs();
            float duration = media.Info.GetDurationMs();
            float d = Mathf.Clamp(time / duration, 0.0f, 1.0f);
            _setVideoSeekSliderValue = d;
            slider.value = d;
            if (media.Control.IsBuffering())
            {
    
    
                float t1 = 0f;
                float t2 = media.Control.GetBufferingProgress();
                if (t2 <= 0f)
                {
    
    
                    if (media.Control.GetBufferedTimeRangeCount() > 0)
                    {
    
    
                        media.Control.GetBufferedTimeRange(0, ref t1, ref t2);
                        t1 /= media.Info.GetDurationMs();
                        t2 /= media.Info.GetDurationMs();
                    }
                }
            }
        }
    }

    /// <summary>
    /// 视频播放
    /// </summary>
    public void OnPlayButton()
    {
    
    
        if (media)
        {
    
    
            media.Control.Play();
        }
    }

    /// <summary>
    /// 视频暂停
    /// </summary>
    public void OnPauseButton()
    {
    
    
        if (media)
        {
    
    
            media.Control.Pause();
        }
    }

    /// <summary>
    /// 更改视频进度
    /// </summary>
    public void OnVideoSeekSlider()
    {
    
    
        if (media && slider && slider.value != _setVideoSeekSliderValue)
        {
    
    
            media.Control.Seek(slider.value * media.Info.GetDurationMs());
        }
    }

    /// <summary>
    /// 显示视频的时长进度
    /// </summary>
    void VideoPlay_time()
    {
    
    
        play_m = (int)(media.Control.GetCurrentTimeMs() * 0.001f / 60);
        play_s = (int)(media.Control.GetCurrentTimeMs() * 0.001f % 60);
        m = (int)(media.Info.GetDurationMs() * 0.001f / 60);
        s = ((int)((media.Info.GetDurationMs() * 0.001f) - m * 60));
        if (play_s < 10)
        {
    
    
            play_time.text = play_m + ":" + "0" + play_s + " / " + m + ":" + s;
        }
        else
        {
    
    
            play_time.text = play_m + ":" + play_s + " / " + m + ":" + s;
        }
    }


    public void OnOpenVideoFile(string name)
    {
    
    
        uGUI.gameObject.SetActive(true);
        media.m_VideoPath = System.IO.Path.Combine(name);
        if (string.IsNullOrEmpty(media.m_VideoPath))
        {
    
    
            media.CloseVideo();
        }
        else
        {
    
    
            media.OpenVideoFromFile(_location, media.m_VideoPath);
        }
    }
    private void OnDisable()
    {
    
    
        isplay = true;
    }
}

The method of adding to the Slider object is as shown in the figure below:
insert image description here
The demo effect is as follows:
insert image description here
Link: https://pan.baidu.com/s/1DVCRfWYVRR15MTdy-xtJDQ
Extraction code: avpr

Guess you like

Origin blog.csdn.net/weixin_43541308/article/details/121034026