Unity 调用外部摄像头

版权声明: https://blog.csdn.net/qq_21153225/article/details/82085606

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

    /// <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);
            //关掉背景
            backGround.gameObject.SetActive(false);
            //
            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 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))
        {
            //打开渲染图
            tt.gameObject.SetActive(true);
            //关掉背景
            backGround.gameObject.SetActive(false);
            //
            WebCamDevice[] devices = WebCamTexture.devices;
            string devicename = devices[0].name;
            webCam = new WebCamTexture(devicename, maxl, maxl, 12);
            webCam.wrapMode = TextureWrapMode.Repeat;
            tt.texture = webCam;
            webCam.Stop();
        }
        tt.gameObject.SetActive(false);
        backGround.gameObject.SetActive(true);
        gameObject.SetActive(false);
    }

注意下:

 if (webCam != null)
            {
                webCam.Stop();
            }

需加上此段代码进行判断,否则你再次调用函数时,无法打开摄像头

猜你喜欢

转载自blog.csdn.net/qq_21153225/article/details/82085606