Unity通過按鈕控制視頻播放與停止


1. 創建Canvas--RawImage。

 

 2. 導入視頻資源(在Assets目錄下新建Video文件夾),直接將視頻拖入Video文件夾。

 

 3. 將導入的視頻拖入第1步新建的RawImage,RawImage右邊的Inspector欄將自動出現Video Player。

將導入的視頻拖入Video Clip。

 

 

 4. 創建按鈕Button,text改成  暫停。

 

 5. 創建C#腳本Movie,控制視頻播放與暫停。腳本如下:

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

public class Movie : MonoBehaviour
{
    public Text text_PlayOrPause;
    public Button button_PlayOrPause;
    private VideoPlayer videoPlayer;
    private RawImage rawImage;
    private int flag = 0;

    //private AudioSource audioSource;
    // Start is called before the first frame update
    void Start()
    {
        videoPlayer = this.GetComponent<VideoPlayer>();
        //audioSource = this.GetComponent<AudioSource>();
        rawImage = this.GetComponent<RawImage>();
        button_PlayOrPause.onClick.AddListener(PlayorPause);
    }

    void Update()
    {
        //判斷視頻播放情況,播放則按鈕顯示暫停,暫停就顯示播放,並更新相關文本
        //沒有視頻則返回,不播放
        if (flag == 0)
        {
            if (videoPlayer.texture == null)
            {
                return;
            }
            //渲染視頻到UGUI
            else
            {
                rawImage.texture = videoPlayer.texture;
                flag++;
            }
        }
    }
    void PlayorPause()
    {
        
        if (videoPlayer.isPlaying == true)
        {
            videoPlayer.Pause();
            //audioSource.Pause();
            text_PlayOrPause.text = "播放";
        }
        else
        {
            videoPlayer.Play();
            //audioSource.Play();
            text_PlayOrPause.text = "暫停";
        }
    }
}

6. 將腳本掛載到Canvas--RawImage並設置相關參數,將第4步創建的Button拖入Button_Play Or Pause,Button下的Text拖入Text_Play Or Pause,如下圖。

 

 7. 運行。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM