NRAudioCapture.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. namespace NRKernal.Record
  10. {
  11. using UnityEngine;
  12. using NRKernal;
  13. using System;
  14. using System.Collections.Generic;
  15. /// <summary>
  16. /// Records a audio from the MR images directly to disk. MR images comes from rgb camera or rgb
  17. /// camera image and virtual image blending. The final audio recording will be stored on the file
  18. /// system in the MP4 format. </summary>
  19. public class NRAudioCapture : IDisposable
  20. {
  21. /// <summary>
  22. /// Indicates whether or not the AudioCapture instance is currently recording audio. </summary>
  23. /// <value> True if this object is recording, false if not. </value>
  24. public bool IsRecording { get; private set; }
  25. /// <summary> Encoder for the capture. </summary>
  26. private AudioEncoder m_AudioEncoder;
  27. private AudioFilterStream m_AudioFilterStream;
  28. public event AudioDataCallBack OnAudioData;
  29. public int BytesPerSample { get { return NativeConstants.RECORD_AUDIO_BYTES_PER_SAMPLE; }}
  30. public int Channels { get { return NativeConstants.RECORD_AUDIO_CHANNEL; }}
  31. public int SamplesPerSec { get { return NativeConstants.RECORD_AUDIO_SAMPLERATE_DEFAULT; }}
  32. /// <summary> Create a NRAudioCapture object. </summary>
  33. public static NRAudioCapture Create()
  34. {
  35. NRAudioCapture capture = new NRAudioCapture();
  36. return capture;
  37. }
  38. /// <summary> Default constructor. </summary>
  39. public NRAudioCapture()
  40. {
  41. IsRecording = false;
  42. }
  43. /// <summary> Finalizer. </summary>
  44. ~NRAudioCapture()
  45. {
  46. }
  47. /// <summary> Dispose must be called to shutdown the AudioCapture instance. </summary>
  48. public void Dispose()
  49. {
  50. if (m_AudioEncoder != null)
  51. {
  52. m_AudioEncoder.Release();
  53. m_AudioEncoder = null;
  54. }
  55. if (m_AudioFilterStream != null)
  56. {
  57. m_AudioFilterStream.Dispose();
  58. m_AudioFilterStream = null;
  59. }
  60. }
  61. /// <summary> Starts recording asynchronous. </summary>
  62. /// <param name="filename"> Filename of the file.</param>
  63. /// <param name="onStartedRecordingVideoCallback"> The on started recording video callback.</param>
  64. public void StartRecordingAsync(string filename, OnStartedRecordingAudioCallback onStartedRecordingAudioCallback)
  65. {
  66. float volumeFactorMic = 1.0f;
  67. float volumeFactorApp = 1.0f;
  68. if (NRDevice.Subsystem.GetDeviceType() == NRDeviceType.NrealLight)
  69. {
  70. volumeFactorMic = NativeConstants.RECORD_VOLUME_MIC;
  71. volumeFactorApp = NativeConstants.RECORD_VOLUME_APP;
  72. }
  73. StartRecordingAsync(filename, onStartedRecordingAudioCallback, volumeFactorMic, volumeFactorApp);
  74. }
  75. /// <summary> Starts recording asynchronous. </summary>
  76. /// <param name="filename"> Filename of the file.</param>
  77. /// <param name="onStartedRecordingAudioCallback"> The on started recording audio callback.</param>
  78. public void StartRecordingAsync(string filename, OnStartedRecordingAudioCallback onStartedRecordingAudioCallback, float volumeFactorMic, float volumeFactorApp)
  79. {
  80. NRDebugger.Info("[AudioCapture] StartRecordingAsync: IsRecording={0}, volFactorMic={1}, volFactorApp={2}", IsRecording, volumeFactorMic, volumeFactorApp);
  81. var result = new AudioCaptureResult();
  82. if (IsRecording)
  83. {
  84. result.resultType = CaptureResultType.UnknownError;
  85. onStartedRecordingAudioCallback?.Invoke(result);
  86. }
  87. else
  88. {
  89. try
  90. {
  91. if (m_AudioFilterStream == null)
  92. {
  93. m_AudioFilterStream = new AudioFilterStream();
  94. }
  95. m_AudioEncoder.AdjustVolume(RecorderIndex.REC_MIC, volumeFactorMic);
  96. m_AudioEncoder.AdjustVolume(RecorderIndex.REC_APP, volumeFactorApp);
  97. m_AudioEncoder.EncodeConfig.SetOutPutPath(filename);
  98. m_AudioEncoder.Start(OnAudioDataCallback);
  99. IsRecording = true;
  100. result.resultType = CaptureResultType.Success;
  101. onStartedRecordingAudioCallback?.Invoke(result);
  102. }
  103. catch (Exception ex)
  104. {
  105. NRDebugger.Warning("[AudioCapture] StartRecordingAsync: {0}\n{1}", ex.Message, ex.StackTrace);
  106. result.resultType = CaptureResultType.UnknownError;
  107. onStartedRecordingAudioCallback?.Invoke(result);
  108. throw;
  109. }
  110. }
  111. }
  112. private void OnAudioDataCallback(IntPtr data, UInt32 size)
  113. {
  114. // NRDebugger.Warning("[AudioCapture] OnAudioDataCallback: size={0}, data={1}", size, data);
  115. if (m_AudioFilterStream != null)
  116. {
  117. m_AudioFilterStream.OnAudioDataRead(data, size);
  118. }
  119. OnAudioData?.Invoke(data, size);
  120. }
  121. public bool FlushAudioData(ref byte[] outBytesData, ref int samples)
  122. {
  123. if (m_AudioFilterStream != null)
  124. {
  125. if (m_AudioFilterStream.Flush(ref outBytesData))
  126. {
  127. samples = outBytesData.Length / Channels / BytesPerSample;
  128. return true;
  129. }
  130. }
  131. return false;
  132. }
  133. /// <summary> Starts audio mode asynchronous. </summary>
  134. /// <param name="setupParams"> Options for controlling the setup.</param>
  135. /// <param name="onAudioModeStartedCallback"> The on audio mode started callback.</param>
  136. /// <param name="autoAdaptBlendMode"> Auto adaption for BlendMode based on supported feature on current device.</param>
  137. public void StartAudioModeAsync(CameraParameters setupParams, OnAudioModeStartedCallback onAudioModeStartedCallback)
  138. {
  139. if (Application.isEditor || Application.platform != RuntimePlatform.Android)
  140. {
  141. StartAudioMode(setupParams, onAudioModeStartedCallback);
  142. return;
  143. }
  144. bool recordMic = setupParams.CaptureAudioMic;
  145. bool recordApp = setupParams.CaptureAudioApplication;
  146. if (recordApp)
  147. {
  148. NRAndroidPermissionsManager.GetInstance().RequestAndroidPermission("android.permission.RECORD_AUDIO").ThenAction((requestResult) =>
  149. {
  150. if (requestResult.IsAllGranted)
  151. {
  152. NRAndroidPermissionsManager.GetInstance().RequestScreenCapture().ThenAction((AndroidJavaObject mediaProjection) =>
  153. {
  154. if (mediaProjection != null)
  155. {
  156. setupParams.mediaProjection = mediaProjection;
  157. StartAudioMode(setupParams, onAudioModeStartedCallback);
  158. }
  159. else
  160. {
  161. NRDebugger.Error("[AudioCapture] Screen capture is denied by user.");
  162. var result = new AudioCaptureResult();
  163. result.resultType = CaptureResultType.UnknownError;
  164. onAudioModeStartedCallback?.Invoke(result);
  165. NRSessionManager.Instance.OprateInitException(new NRPermissionDenyError(NativeConstants.ScreenCaptureDenyErrorTip));
  166. }
  167. });
  168. }
  169. else {
  170. NRDebugger.Error("[AudioCapture] Record audio need the permission of 'android.permission.RECORD_AUDIO'.");
  171. var result = new AudioCaptureResult();
  172. result.resultType = CaptureResultType.UnknownError;
  173. onAudioModeStartedCallback?.Invoke(result);
  174. NRSessionManager.Instance.OprateInitException(new NRPermissionDenyError(NativeConstants.AudioPermissionDenyErrorTip));
  175. }
  176. });
  177. }
  178. else if (recordMic)
  179. {
  180. NRAndroidPermissionsManager.GetInstance().RequestAndroidPermission("android.permission.RECORD_AUDIO").ThenAction((requestResult) =>
  181. {
  182. if (requestResult.IsAllGranted)
  183. {
  184. StartAudioMode(setupParams, onAudioModeStartedCallback);
  185. }
  186. else {
  187. NRDebugger.Error("[AudioCapture] Record audio need the permission of 'android.permission.RECORD_AUDIO'.");
  188. var result = new AudioCaptureResult();
  189. result.resultType = CaptureResultType.UnknownError;
  190. onAudioModeStartedCallback?.Invoke(result);
  191. NRSessionManager.Instance.OprateInitException(new NRPermissionDenyError(NativeConstants.AudioPermissionDenyErrorTip));
  192. }
  193. });
  194. }
  195. else
  196. {
  197. StartAudioMode(setupParams, onAudioModeStartedCallback);
  198. }
  199. }
  200. private void StartAudioMode(CameraParameters setupParams, OnAudioModeStartedCallback onAudioModeStartedCallback)
  201. {
  202. setupParams.camMode = CamMode.None;
  203. if (setupParams.frameRate <= 0)
  204. NRDebugger.Warning("[AudioCapture] frameRate need to be bigger than zero");
  205. m_AudioEncoder = new AudioEncoder();
  206. m_AudioEncoder.Config(setupParams);
  207. var result = new AudioCaptureResult();
  208. result.resultType = CaptureResultType.Success;
  209. onAudioModeStartedCallback?.Invoke(result);
  210. }
  211. /// <summary> Stops recording asynchronous. </summary>
  212. /// <param name="onStoppedRecordingAudioCallback"> The on stopped recording audio callback.</param>
  213. public void StopRecordingAsync(OnStoppedRecordingAudioCallback onStoppedRecordingAudioCallback)
  214. {
  215. var result = new AudioCaptureResult();
  216. if (!IsRecording)
  217. {
  218. result.resultType = CaptureResultType.UnknownError;
  219. onStoppedRecordingAudioCallback?.Invoke(result);
  220. }
  221. else
  222. {
  223. try
  224. {
  225. m_AudioEncoder.Stop();
  226. IsRecording = false;
  227. result.resultType = CaptureResultType.Success;
  228. onStoppedRecordingAudioCallback?.Invoke(result);
  229. }
  230. catch (Exception)
  231. {
  232. result.resultType = CaptureResultType.UnknownError;
  233. onStoppedRecordingAudioCallback?.Invoke(result);
  234. throw;
  235. }
  236. }
  237. }
  238. /// <summary> Stops video mode asynchronous. </summary>
  239. /// <param name="onAudioModeStoppedCallback"> The on video mode stopped callback.</param>
  240. public void StopAudioModeAsync(OnAudioModeStoppedCallback onAudioModeStoppedCallback)
  241. {
  242. m_AudioEncoder?.Release();
  243. m_AudioEncoder = null;
  244. var result = new AudioCaptureResult();
  245. result.resultType = CaptureResultType.Success;
  246. onAudioModeStoppedCallback?.Invoke(result);
  247. }
  248. /// <summary> Contains the result of the capture request. </summary>
  249. public enum CaptureResultType
  250. {
  251. /// <summary>
  252. /// Specifies that the desired operation was successful.
  253. /// </summary>
  254. Success = 0,
  255. /// <summary>
  256. /// Specifies that an unknown error occurred.
  257. /// </summary>
  258. UnknownError = 1
  259. }
  260. /// <summary>
  261. /// A data container that contains the result information of a audio recording operation. </summary>
  262. public struct AudioCaptureResult
  263. {
  264. /// <summary>
  265. /// A generic result that indicates whether or not the AudioCapture operation succeeded. </summary>
  266. public CaptureResultType resultType;
  267. /// <summary> The specific HResult value. </summary>
  268. public long hResult;
  269. /// <summary> Indicates whether or not the operation was successful. </summary>
  270. /// <value> True if success, false if not. </value>
  271. public bool success
  272. {
  273. get
  274. {
  275. return resultType == CaptureResultType.Success;
  276. }
  277. }
  278. }
  279. /// <summary> Called when the web camera begins recording the audio. </summary>
  280. /// <param name="result"> Indicates whether or not audio recording started successfully.</param>
  281. public delegate void OnStartedRecordingAudioCallback(AudioCaptureResult result);
  282. /// <summary> Called when audio mode has been started. </summary>
  283. /// <param name="result"> Indicates whether or not audio mode was successfully activated.</param>
  284. public delegate void OnAudioModeStartedCallback(AudioCaptureResult result);
  285. /// <summary> Called when audio mode has been stopped. </summary>
  286. /// <param name="result"> Indicates whether or not audio mode was successfully deactivated.</param>
  287. public delegate void OnAudioModeStoppedCallback(AudioCaptureResult result);
  288. /// <summary> Called when the audio recording has been saved to the file system. </summary>
  289. /// <param name="result"> Indicates whether or not audio recording was saved successfully to the
  290. /// file system.</param>
  291. public delegate void OnStoppedRecordingAudioCallback(AudioCaptureResult result);
  292. }
  293. }