MultiSourceManager.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using UnityEngine;
  2. using System.Collections;
  3. using Windows.Kinect;
  4. public class MultiSourceManager : MonoBehaviour {
  5. public int ColorWidth { get; private set; }
  6. public int ColorHeight { get; private set; }
  7. private KinectSensor _Sensor;
  8. private MultiSourceFrameReader _Reader;
  9. private Texture2D _ColorTexture;
  10. private ushort[] _DepthData;
  11. private byte[] _ColorData;
  12. public Texture2D GetColorTexture()
  13. {
  14. return _ColorTexture;
  15. }
  16. public ushort[] GetDepthData()
  17. {
  18. return _DepthData;
  19. }
  20. void Start ()
  21. {
  22. _Sensor = KinectSensor.GetDefault();
  23. if (_Sensor != null)
  24. {
  25. _Reader = _Sensor.OpenMultiSourceFrameReader(FrameSourceTypes.Color | FrameSourceTypes.Depth);
  26. var colorFrameDesc = _Sensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Rgba);
  27. ColorWidth = colorFrameDesc.Width;
  28. ColorHeight = colorFrameDesc.Height;
  29. _ColorTexture = new Texture2D(colorFrameDesc.Width, colorFrameDesc.Height, TextureFormat.RGBA32, false);
  30. _ColorData = new byte[colorFrameDesc.BytesPerPixel * colorFrameDesc.LengthInPixels];
  31. var depthFrameDesc = _Sensor.DepthFrameSource.FrameDescription;
  32. _DepthData = new ushort[depthFrameDesc.LengthInPixels];
  33. if (!_Sensor.IsOpen)
  34. {
  35. _Sensor.Open();
  36. }
  37. }
  38. }
  39. void Update ()
  40. {
  41. if (_Reader != null)
  42. {
  43. var frame = _Reader.AcquireLatestFrame();
  44. if (frame != null)
  45. {
  46. var colorFrame = frame.ColorFrameReference.AcquireFrame();
  47. if (colorFrame != null)
  48. {
  49. var depthFrame = frame.DepthFrameReference.AcquireFrame();
  50. if (depthFrame != null)
  51. {
  52. colorFrame.CopyConvertedFrameDataToArray(_ColorData, ColorImageFormat.Rgba);
  53. _ColorTexture.LoadRawTextureData(_ColorData);
  54. _ColorTexture.Apply();
  55. depthFrame.CopyFrameDataToArray(_DepthData);
  56. depthFrame.Dispose();
  57. depthFrame = null;
  58. }
  59. colorFrame.Dispose();
  60. colorFrame = null;
  61. }
  62. frame = null;
  63. }
  64. }
  65. }
  66. void OnApplicationQuit()
  67. {
  68. if (_Reader != null)
  69. {
  70. _Reader.Dispose();
  71. _Reader = null;
  72. }
  73. if (_Sensor != null)
  74. {
  75. if (_Sensor.IsOpen)
  76. {
  77. _Sensor.Close();
  78. }
  79. _Sensor = null;
  80. }
  81. }
  82. }