using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
struct CameraSetting
{
public int width;
public int height;
public int framerate;
}
public class WebCameraController : MonoBehaviour
{
static WebCamTexture camTexture;
public RawImage m_img;
string deviceKey = "";
int curId=0;
int curSettingid = 0;
List<CameraSetting> settinglist = new List<CameraSetting>();
// Start is called before the first frame update
void Start()
{
m_img = GetComponent<RawImage>();
CameraSetting setting = new CameraSetting();
setting.width = Screen.width;
setting.height = Screen.height;
setting.framerate = 60;
settinglist.Add(setting);
CameraSetting setting2 = new CameraSetting();
setting2.width = Screen.width;
setting2.height = Screen.height;
setting2.framerate = 30;
settinglist.Add(setting2);
CameraSetting setting3 = new CameraSetting();
setting3.width = Screen.width / 2;
setting3.height = Screen.height / 2;
setting3.framerate = 60;
settinglist.Add(setting3);
CameraSetting setting4 = new CameraSetting();
setting4.width = Screen.width / 2;
setting4.height = Screen.height / 2;
setting4.framerate = 30;
settinglist.Add(setting4);
StartCoroutine(CallCamera());
}
string getDeviceNameByKey(string key)
{
WebCamDevice[] cameraDevices = WebCamTexture.devices;
foreach(WebCamDevice device in cameraDevices)
{
if(device.name.Contains(key))
{
return device.name;
}
}
return "";
}
string getDeviceNameById()
{
WebCamDevice[] cameraDevices = WebCamTexture.devices;
if (cameraDevices.Length == 0)
{
MessageBox.instance.showMsg("没有找到摄像设备");
}
return cameraDevices[curId].name;
}
IEnumerator CallCamera()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if(Application.HasUserAuthorization(UserAuthorization.WebCam))
{
if (camTexture != null)
camTexture.Stop();
string deviceName = getDeviceNameById();
if(string.IsNullOrEmpty(deviceName))
{
Debug.Log("没有找到logi相机设备");
yield break;
}
camTexture = new WebCamTexture(deviceName, settinglist[curSettingid].width, settinglist[curSettingid].height, settinglist[curSettingid].framerate);
Debug.Log("Screen Info:" + Screen.width + " : " + Screen.height);
m_img.canvasRenderer.SetTexture(camTexture);
camTexture.Play();
}
}
// Update is called once per frame
void Update()
{
// 通过F1键切换相机
if (Input.GetKeyDown(KeyCode.F1))
{
WebCamDevice[] cameraDevices = WebCamTexture.devices;
curId++;
if (curId > cameraDevices.Length - 1) curId = 0;
Debug.Log("当前使用的设备id=" + curId);
StartCoroutine(CallCamera());
}
// 通过F2切换分辨率
if (Input.GetKeyDown(KeyCode.F2))
{
curSettingid++;
if (curSettingid > 3)
curSettingid = 0;
StartCoroutine(CallCamera());
}
}
}