using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class WebcamControllerPanel : PanelBasic
{
public RawImage camera_rawimage;//相机渲染的UI
//public GameObject quad;//相机渲染的GameObject
private WebCamTexture webCamTexture;
private Coroutine open_camera;
public delegate void OpenCameraDelegate(string _msg, string _type);
public OpenCameraDelegate open_camera_msg;
void Start()
{
}
private void Update()
{
if (Input.GetKey(KeyCode.H))
{
webCamTexture.Stop();
}
if (Input.GetKey(KeyCode.M))
{
webCamTexture.Play();
}
}
///
/// 打开摄像机
///
public void ToOpenCamera()
{
open_camera = StartCoroutine("OpenCamera");
}
public IEnumerator OpenCamera()
{
int maxl = Screen.width;
if (Screen.height > Screen.width)
{
maxl = Screen.height;
}
// 申请摄像头权限
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
if (webCamTexture != null)
{
webCamTexture.Stop();
}
//打开渲染图
if (camera_rawimage != null)
{
camera_rawimage.gameObject.SetActive(true);
}
//if (quad != null)
//{
// quad.gameObject.SetActive(true);
//}
// 监控第一次授权,是否获得到设备(因为很可能第一次授权了,但是获得不到设备,这里这样避免)
// 多次 都没有获得设备,可能就是真没有摄像头,结束获取 camera
int i = 0;
while (WebCamTexture.devices.Length <= 0 && 1 < 300)
{
yield return new WaitForEndOfFrame();
i++;
}
WebCamDevice[] devices = WebCamTexture.devices;//获取可用设备
if (WebCamTexture.devices.Length <= 0)
{
Debug.LogError("没有摄像头设备,请检查");
open_camera_msg?.Invoke("没有摄像头设备,请检查!", "warning");
}
else
{
string devicename = devices[0].name;
webCamTexture = new WebCamTexture(devicename, maxl, maxl == Screen.height ? Screen.width : Screen.height, 30)
{
wrapMode = TextureWrapMode.Repeat
};
// 渲染到 UI 或者 游戏物体上
if (camera_rawimage != null)
{
camera_rawimage.texture = webCamTexture;
}
//if (quad != null)
//{
// quad.GetComponent().material.mainTexture = webCamTexture;
//}
webCamTexture.Play();
open_camera_msg?.Invoke("摄像头已打开", "log");
}
}
else
{
Debug.LogError("未获得读取摄像头权限");
open_camera_msg?.Invoke("未获得读取摄像头权限!", "warning");
}
}
private void OnApplicationPause(bool pause)
{
// 应用暂停的时候暂停camera,继续的时候继续使用
if (webCamTexture != null)
{
if (pause)
{
webCamTexture.Pause();
}
else
{
webCamTexture.Play();
}
}
}
public void OnActive(bool _use_real_camera)
{
OnActive();
if (_use_real_camera)
{
ToOpenCamera();
}
}
public override void OnActive(Image _main_panel = null, Image _mask = null, Action _callback = null)
{
base.OnActive(_main_panel, _mask, _callback);
camera_rawimage.gameObject.SetActive(true);
}
public override void OnNagetive(bool _active_last_panel)
{
base.OnNagetive(_active_last_panel);
if (open_camera != null)
{
StopCoroutine(open_camera);
open_camera_msg?.Invoke("摄像头已关闭", "log");
//后添加的用来在停止摄像头的时候禁用摄像头的方法
if (webCamTexture != null)
{
webCamTexture.Stop();
}
}
camera_rawimage.gameObject.SetActive(false);
}
private void OnDestroy()
{
if (webCamTexture != null)
{
webCamTexture.Stop();
}
}
}