VideoCapture2LocalExample.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. using NRKernal.Record;
  10. using System;
  11. using System.IO;
  12. using System.Collections;
  13. using System.Linq;
  14. using UnityEngine;
  15. using UnityEngine.UI;
  16. namespace NRKernal.NRExamples
  17. {
  18. #if UNITY_ANDROID && !UNITY_EDITOR
  19. using GalleryDataProvider = NativeGalleryDataProvider;
  20. #else
  21. using GalleryDataProvider = MockGalleryDataProvider;
  22. #endif
  23. /// <summary> A video capture 2 local example. </summary>
  24. [HelpURL("https://developer.nreal.ai/develop/unity/video-capture")]
  25. public class VideoCapture2LocalExample : MonoBehaviour
  26. {
  27. [SerializeField] private Button m_PlayButton;
  28. [SerializeField] private NRPreviewer m_Previewer;
  29. [SerializeField] private Slider m_SliderMic;
  30. [SerializeField] private Text m_TextMic;
  31. [SerializeField] private Slider m_SliderApp;
  32. [SerializeField] private Text m_TextApp;
  33. public BlendMode blendMode = BlendMode.Blend;
  34. public ResolutionLevel resolutionLevel;
  35. public LayerMask cullingMask = -1;
  36. public NRVideoCapture.AudioState audioState = NRVideoCapture.AudioState.ApplicationAudio;
  37. public bool useGreenBackGround = false;
  38. public enum ResolutionLevel
  39. {
  40. High,
  41. Middle,
  42. Low,
  43. }
  44. /// <summary> Save the video to Application.persistentDataPath. </summary>
  45. /// <value> The full pathname of the video save file. </value>
  46. public string VideoSavePath
  47. {
  48. get
  49. {
  50. string timeStamp = Time.time.ToString().Replace(".", "").Replace(":", "");
  51. string filename = string.Format("Nreal_Record_{0}.mp4", timeStamp);
  52. return Path.Combine(Application.persistentDataPath, filename);
  53. }
  54. }
  55. GalleryDataProvider galleryDataTool;
  56. void Awake()
  57. {
  58. if (m_SliderMic != null)
  59. {
  60. m_SliderMic.maxValue = 10.0f;
  61. m_SliderMic.minValue = 0.1f;
  62. m_SliderMic.value = 1;
  63. m_SliderMic.onValueChanged.AddListener(OnSlideMicValueChange);
  64. }
  65. if (m_SliderApp != null)
  66. {
  67. m_SliderApp.maxValue = 10.0f;
  68. m_SliderApp.minValue = 0.1f;
  69. m_SliderApp.value = 1;
  70. m_SliderApp.onValueChanged.AddListener(OnSlideAppValueChange);
  71. }
  72. RefreshUIState();
  73. }
  74. void OnSlideMicValueChange(float val)
  75. {
  76. if (m_VideoCapture != null)
  77. {
  78. VideoEncoder encoder = m_VideoCapture.GetContext().GetEncoder() as VideoEncoder;
  79. if (encoder != null)
  80. encoder.AdjustVolume(RecorderIndex.REC_MIC, val);
  81. }
  82. RefreshUIState();
  83. }
  84. void OnSlideAppValueChange(float val)
  85. {
  86. if (m_VideoCapture != null)
  87. {
  88. VideoEncoder encoder = m_VideoCapture.GetContext().GetEncoder() as VideoEncoder;
  89. if (encoder != null)
  90. encoder.AdjustVolume(RecorderIndex.REC_APP, val);
  91. }
  92. RefreshUIState();
  93. }
  94. /// <summary> The video capture. </summary>
  95. NRVideoCapture m_VideoCapture = null;
  96. void CreateVideoCapture(Action callback)
  97. {
  98. NRVideoCapture.CreateAsync(false, delegate (NRVideoCapture videoCapture)
  99. {
  100. NRDebugger.Info("Created VideoCapture Instance!");
  101. if (videoCapture != null)
  102. {
  103. m_VideoCapture = videoCapture;
  104. callback?.Invoke();
  105. }
  106. else
  107. {
  108. NRDebugger.Error("Failed to create VideoCapture Instance!");
  109. }
  110. });
  111. }
  112. public void OnClickPlayButton()
  113. {
  114. if (m_VideoCapture == null)
  115. {
  116. CreateVideoCapture(() =>
  117. {
  118. StartVideoCapture();
  119. });
  120. }
  121. else if (m_VideoCapture.IsRecording)
  122. {
  123. this.StopVideoCapture();
  124. }
  125. else
  126. {
  127. this.StartVideoCapture();
  128. }
  129. }
  130. void RefreshUIState()
  131. {
  132. bool flag = m_VideoCapture == null || !m_VideoCapture.IsRecording;
  133. m_PlayButton.GetComponent<Image>().color = flag ? Color.red : Color.green;
  134. if (m_TextMic != null && m_SliderMic != null)
  135. m_TextMic.text = m_SliderMic.value.ToString();
  136. if (m_TextApp != null && m_SliderApp != null)
  137. m_TextApp.text = m_SliderApp.value.ToString();
  138. }
  139. /// <summary> Starts video capture. </summary>
  140. public void StartVideoCapture()
  141. {
  142. if (m_VideoCapture == null || m_VideoCapture.IsRecording)
  143. {
  144. NRDebugger.Warning("Can not start video capture!");
  145. return;
  146. }
  147. CameraParameters cameraParameters = new CameraParameters();
  148. Resolution cameraResolution = GetResolutionByLevel(resolutionLevel);
  149. cameraParameters.hologramOpacity = 0.0f;
  150. cameraParameters.frameRate = cameraResolution.refreshRate;
  151. cameraParameters.cameraResolutionWidth = cameraResolution.width;
  152. cameraParameters.cameraResolutionHeight = cameraResolution.height;
  153. cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;
  154. // Set the blend mode.
  155. cameraParameters.blendMode = blendMode;
  156. // Set audio state, audio record needs the permission of "android.permission.RECORD_AUDIO",
  157. // Add it to your "AndroidManifest.xml" file in "Assets/Plugin".
  158. cameraParameters.audioState = audioState;
  159. m_VideoCapture.StartVideoModeAsync(cameraParameters, OnStartedVideoCaptureMode, true);
  160. }
  161. private Resolution GetResolutionByLevel(ResolutionLevel level)
  162. {
  163. var resolutions = NRVideoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height);
  164. Resolution resolution = new Resolution();
  165. switch (level)
  166. {
  167. case ResolutionLevel.High:
  168. resolution = resolutions.ElementAt(0);
  169. break;
  170. case ResolutionLevel.Middle:
  171. resolution = resolutions.ElementAt(1);
  172. break;
  173. case ResolutionLevel.Low:
  174. resolution = resolutions.ElementAt(2);
  175. break;
  176. default:
  177. break;
  178. }
  179. return resolution;
  180. }
  181. /// <summary> Stops video capture. </summary>
  182. public void StopVideoCapture()
  183. {
  184. if (m_VideoCapture == null || !m_VideoCapture.IsRecording)
  185. {
  186. NRDebugger.Warning("Can not stop video capture!");
  187. return;
  188. }
  189. NRDebugger.Info("Stop Video Capture!");
  190. m_VideoCapture.StopRecordingAsync(OnStoppedRecordingVideo);
  191. m_Previewer.SetData(null, false);
  192. }
  193. /// <summary> Executes the 'started video capture mode' action. </summary>
  194. /// <param name="result"> The result.</param>
  195. void OnStartedVideoCaptureMode(NRVideoCapture.VideoCaptureResult result)
  196. {
  197. if (!result.success)
  198. {
  199. NRDebugger.Info("Started Video Capture Mode faild!");
  200. return;
  201. }
  202. NRDebugger.Info("Started Video Capture Mode!");
  203. float volumeMic = m_SliderMic != null ? m_SliderMic.value : NativeConstants.RECORD_VOLUME_MIC;
  204. float volumeApp = m_SliderApp != null ? m_SliderApp.value : NativeConstants.RECORD_VOLUME_APP;
  205. m_VideoCapture.StartRecordingAsync(VideoSavePath, OnStartedRecordingVideo, volumeMic, volumeApp);
  206. // Set preview texture.
  207. m_Previewer.SetData(m_VideoCapture.PreviewTexture, true);
  208. }
  209. /// <summary> Executes the 'started recording video' action. </summary>
  210. /// <param name="result"> The result.</param>
  211. void OnStartedRecordingVideo(NRVideoCapture.VideoCaptureResult result)
  212. {
  213. if (!result.success)
  214. {
  215. NRDebugger.Info("Started Recording Video Faild!");
  216. return;
  217. }
  218. NRDebugger.Info("Started Recording Video!");
  219. if (useGreenBackGround)
  220. {
  221. // Set green background color.
  222. m_VideoCapture.GetContext().GetBehaviour().SetBackGroundColor(Color.green);
  223. }
  224. m_VideoCapture.GetContext().GetBehaviour().SetCameraMask(cullingMask.value);
  225. RefreshUIState();
  226. }
  227. /// <summary> Executes the 'stopped recording video' action. </summary>
  228. /// <param name="result"> The result.</param>
  229. void OnStoppedRecordingVideo(NRVideoCapture.VideoCaptureResult result)
  230. {
  231. if (!result.success)
  232. {
  233. NRDebugger.Info("Stopped Recording Video Faild!");
  234. return;
  235. }
  236. NRDebugger.Info("Stopped Recording Video!");
  237. m_VideoCapture.StopVideoModeAsync(OnStoppedVideoCaptureMode);
  238. }
  239. /// <summary> Executes the 'stopped video capture mode' action. </summary>
  240. /// <param name="result"> The result.</param>
  241. void OnStoppedVideoCaptureMode(NRVideoCapture.VideoCaptureResult result)
  242. {
  243. NRDebugger.Info("Stopped Video Capture Mode!");
  244. RefreshUIState();
  245. var encoder = m_VideoCapture.GetContext().GetEncoder() as VideoEncoder;
  246. string path = encoder.EncodeConfig.outPutPath;
  247. string filename = string.Format("Nreal_Shot_Video_{0}.mp4", NRTools.GetTimeStamp().ToString());
  248. StartCoroutine(DelayInsertVideoToGallery(path, filename, "Record"));
  249. // Release video capture resource.
  250. m_VideoCapture.Dispose();
  251. m_VideoCapture = null;
  252. }
  253. void OnDestroy()
  254. {
  255. // Release video capture resource.
  256. m_VideoCapture?.Dispose();
  257. m_VideoCapture = null;
  258. }
  259. IEnumerator DelayInsertVideoToGallery(string originFilePath, string displayName, string folderName)
  260. {
  261. yield return new WaitForSeconds(0.1f);
  262. InsertVideoToGallery(originFilePath, displayName, folderName);
  263. }
  264. public void InsertVideoToGallery(string originFilePath, string displayName, string folderName)
  265. {
  266. NRDebugger.Info("InsertVideoToGallery: {0}, {1} => {2}", displayName, originFilePath, folderName);
  267. if (galleryDataTool == null)
  268. {
  269. galleryDataTool = new GalleryDataProvider();
  270. }
  271. galleryDataTool.InsertVideo(originFilePath, displayName, folderName);
  272. }
  273. }
  274. }