Unity 调用外置摄像头

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

public class WebCamera : MonoBehaviour
{

    WebCamTexture webCam;
    public RawImage tt;
    // 背景
    public Image backGround;

    /// <summary>
    /// 打开摄像机
    /// </summary>
    /// 
    private void Start()
    {
        OpenCameraBackground();
    }

    /// <summary>
    /// 初始化相机
    /// </summary>
    public void OpenCameraBackground()
    {
        StartCoroutine("startCam");
    }
    public IEnumerator startCam()
    {
        int maxl = Screen.width;
        if (Screen.height > Screen.width)
        {
            maxl = Screen.height;
        }
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            if (webCam != null)
            {
                webCam.Stop();
            }
            //打开渲染图
            tt.gameObject.SetActive(true);
            //关掉背景

            WebCamDevice[] devices = WebCamTexture.devices;
            string devicename = devices[0].name;
            webCam = new WebCamTexture(devicename, maxl, maxl, 12);
            webCam.wrapMode = TextureWrapMode.Repeat;
            tt.texture = webCam;
            webCam.Play();
        }
    }

    /// <summary>
    /// 启动相机
    /// </summary>
    public void PlayCamera()
    {
        if (webCam)
        {
            if (!webCam.isPlaying)
                webCam.Play();
        }
    }

    /// <summary>
    /// 关闭摄像机
    /// </summary>
    public void CloseCameraBackground()
    {
        StartCoroutine(stopCam());
    }

    public IEnumerator stopCam()
    {
        int maxl = Screen.width;
        if (Screen.height > Screen.width)
        {
            maxl = Screen.height;
        }
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            if (webCam != null)
            {
                if (webCam.isPlaying)
                    webCam.Pause();
            }
        }
    }

    public void Update()
    {
        if (Input.GetKeyDown("o"))
        {
            PlayCamera();
        }

        if (Input.GetKeyDown("s"))
        {
            CloseCameraBackground();
        }

        //Debug.Log(webCam.isPlaying);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容