| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- using UnityEngine;
- using UnityEngine.UI;
- public class ZIMWebCamera : MonoBehaviour {
- public int cameraIndex = 0;
- public int width = 1280;
- public int height = 720;
- public int fps = 60;
- public RawImage rawImage;
- private WebCamTexture _webCamTexture;
- public WebCamTexture webCamTexture { get => _webCamTexture; }
- public Vector2 Size => new Vector2(width, height);
- void Start()
- {
- OnClick_Open();
- }
- void Update()
- {
- if (_webCamTexture) {
- width = _webCamTexture.width;
- height = _webCamTexture.height;
- fps = (int)_webCamTexture.requestedFPS;
- }
- }
- public Vector2Int IndexToCoord(int i)
- {
- var y = i / width;
- var x = i % width;
- return new Vector2Int(x, y);
- }
- public int CoordToIndex(int x, int y)
- {
- return y * width + x;
- }
- public void OnClick_Open()
- {
- if (_webCamTexture != null)
- {
- Debug.LogError("开启失败,请先关闭正在使用的摄像头!");
- return;
- }
- if (Application.HasUserAuthorization(UserAuthorization.WebCam))
- {
- WebCamDevice[] devices = WebCamTexture.devices;
- if (devices.Length == 0)
- {
- Debug.LogError("开启失败,没找到可用的摄像头!");
- return;
- }
- if (devices.Length < cameraIndex + 1)
- {
- Debug.LogError("开启失败,没有对应序号的摄像头!");
- return;
- }
- string deviceName = devices[cameraIndex].name;
- _webCamTexture = new WebCamTexture(deviceName, width, height, fps);
- //try
- {
- _webCamTexture.Play();
- if (rawImage) rawImage.texture = _webCamTexture;
- Debug.Log("成功开启摄像头 " + deviceName);
- }
- //catch (System.Exception e)
- //{
- // Debug.Log("摄像头开启失败 " + deviceName + ", 可能有其他软件占用, " + e.Message);
- //}
- //o0WebCam = new o0.Project.WebCam(_webCamTexture);
- /*
- Task.Run(() => {
- if(_webCamTexture.didUpdateThisFrame)
- });/**/
- }
- else
- {
- Debug.LogError("开启失败,用户未授予摄像头权限!");
- }
- }
- public void OnClick_Close()
- {
- if (_webCamTexture != null)
- {
- _webCamTexture.Stop();
- _webCamTexture = null;
- if (rawImage) rawImage.texture = null;
- Debug.Log("成功关闭摄像头");
- //o0WebCam.Dispose();
- //o0WebCam = null;
- }
- }
- }
|