ZIMWebCamera.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. public class ZIMWebCamera : MonoBehaviour {
  4. public int cameraIndex = 0;
  5. public int width = 1280;
  6. public int height = 720;
  7. public int fps = 60;
  8. public RawImage rawImage;
  9. private WebCamTexture _webCamTexture;
  10. public WebCamTexture webCamTexture { get => _webCamTexture; }
  11. public Vector2 Size => new Vector2(width, height);
  12. void Start()
  13. {
  14. OnClick_Open();
  15. }
  16. void Update()
  17. {
  18. if (_webCamTexture) {
  19. width = _webCamTexture.width;
  20. height = _webCamTexture.height;
  21. fps = (int)_webCamTexture.requestedFPS;
  22. }
  23. }
  24. public Vector2Int IndexToCoord(int i)
  25. {
  26. var y = i / width;
  27. var x = i % width;
  28. return new Vector2Int(x, y);
  29. }
  30. public int CoordToIndex(int x, int y)
  31. {
  32. return y * width + x;
  33. }
  34. public void OnClick_Open()
  35. {
  36. if (_webCamTexture != null)
  37. {
  38. Debug.LogError("开启失败,请先关闭正在使用的摄像头!");
  39. return;
  40. }
  41. if (Application.HasUserAuthorization(UserAuthorization.WebCam))
  42. {
  43. WebCamDevice[] devices = WebCamTexture.devices;
  44. if (devices.Length == 0)
  45. {
  46. Debug.LogError("开启失败,没找到可用的摄像头!");
  47. return;
  48. }
  49. if (devices.Length < cameraIndex + 1)
  50. {
  51. Debug.LogError("开启失败,没有对应序号的摄像头!");
  52. return;
  53. }
  54. string deviceName = devices[cameraIndex].name;
  55. _webCamTexture = new WebCamTexture(deviceName, width, height, fps);
  56. //try
  57. {
  58. _webCamTexture.Play();
  59. if (rawImage) rawImage.texture = _webCamTexture;
  60. Debug.Log("成功开启摄像头 " + deviceName);
  61. }
  62. //catch (System.Exception e)
  63. //{
  64. // Debug.Log("摄像头开启失败 " + deviceName + ", 可能有其他软件占用, " + e.Message);
  65. //}
  66. //o0WebCam = new o0.Project.WebCam(_webCamTexture);
  67. /*
  68. Task.Run(() => {
  69. if(_webCamTexture.didUpdateThisFrame)
  70. });/**/
  71. }
  72. else
  73. {
  74. Debug.LogError("开启失败,用户未授予摄像头权限!");
  75. }
  76. }
  77. public void OnClick_Close()
  78. {
  79. if (_webCamTexture != null)
  80. {
  81. _webCamTexture.Stop();
  82. _webCamTexture = null;
  83. if (rawImage) rawImage.texture = null;
  84. Debug.Log("成功关闭摄像头");
  85. //o0WebCam.Dispose();
  86. //o0WebCam = null;
  87. }
  88. }
  89. }