CustomCaptureAudio.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. using System;
  2. using System.Threading;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.Serialization;
  6. using System.Runtime.InteropServices;
  7. using Agora.Rtc;
  8. using Agora.Util;
  9. using Logger = Agora.Util.Logger;
  10. using RingBuffer;
  11. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.CustomCaptureAudio
  12. {
  13. public class CustomCaptureAudio : MonoBehaviour
  14. {
  15. [FormerlySerializedAs("appIdInput")]
  16. [SerializeField]
  17. private AppIdInput _appIdInput;
  18. [Header("_____________Basic Configuration_____________")]
  19. [FormerlySerializedAs("APP_ID")]
  20. [SerializeField]
  21. private string _appID = "";
  22. [FormerlySerializedAs("TOKEN")]
  23. [SerializeField]
  24. private string _token = "";
  25. [FormerlySerializedAs("CHANNEL_NAME")]
  26. [SerializeField]
  27. private string _channelName = "";
  28. public Text LogText;
  29. internal Logger Log;
  30. internal IRtcEngine RtcEngine = null;
  31. private const int CHANNEL = 1;
  32. // Please do not change this value because Unity re-samples the sample rate to 48000.
  33. private const int SAMPLE_RATE = 48000;
  34. private const int PUSH_FREQ_PER_SEC = 100;
  35. private RingBuffer<byte> _audioBuffer;
  36. private bool _startConvertSignal = false;
  37. private Thread _pushAudioFrameThread;
  38. private System.Object _pushAudioFrameThreadSignal = new System.Object();
  39. private int _count;
  40. private bool _startSignal = false;
  41. // Use this for initialization
  42. private void Start()
  43. {
  44. LoadAssetData();
  45. if (CheckAppId())
  46. {
  47. InitRtcEngine();
  48. SetExternalAudioSource();
  49. JoinChannel();
  50. StartPushAudioFrame();
  51. }
  52. }
  53. // Update is called once per frame
  54. private void Update()
  55. {
  56. PermissionHelper.RequestMicrophontPermission();
  57. }
  58. //Show data in AgoraBasicProfile
  59. [ContextMenu("ShowAgoraBasicProfileData")]
  60. private void LoadAssetData()
  61. {
  62. if (_appIdInput == null) return;
  63. _appID = _appIdInput.appID;
  64. _token = _appIdInput.token;
  65. _channelName = _appIdInput.channelName;
  66. }
  67. private bool CheckAppId()
  68. {
  69. Log = new Logger(LogText);
  70. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  71. }
  72. private void InitRtcEngine()
  73. {
  74. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  75. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  76. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  77. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  78. RtcEngine.Initialize(context);
  79. RtcEngine.InitEventHandler(new UserEventHandler(this));
  80. }
  81. private void SetExternalAudioSource()
  82. {
  83. var nRet = RtcEngine.SetExternalAudioSource(true, SAMPLE_RATE, CHANNEL, 1);
  84. this.Log.UpdateLog("SetExternalAudioSource nRet:" + nRet);
  85. }
  86. private void StartPushAudioFrame()
  87. {
  88. // 1-sec-length buffer
  89. var bufferLength = SAMPLE_RATE * CHANNEL;
  90. _audioBuffer = new RingBuffer<byte>(bufferLength, true);
  91. _startConvertSignal = true;
  92. _pushAudioFrameThread = new Thread(PushAudioFrameThread);
  93. _pushAudioFrameThread.Start();
  94. }
  95. private void JoinChannel()
  96. {
  97. RtcEngine.SetAudioProfile(AUDIO_PROFILE_TYPE.AUDIO_PROFILE_MUSIC_HIGH_QUALITY,
  98. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  99. RtcEngine.EnableAudio();
  100. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  101. RtcEngine.JoinChannel(_token, _channelName, "");
  102. }
  103. private void OnLeaveBtnClick()
  104. {
  105. RtcEngine.LeaveChannel();
  106. }
  107. private void OnDestroy()
  108. {
  109. Debug.Log("OnDestroy");
  110. if (RtcEngine == null) return;
  111. lock (_pushAudioFrameThreadSignal)
  112. {
  113. RtcEngine.InitEventHandler(null);
  114. RtcEngine.LeaveChannel();
  115. RtcEngine.Dispose();
  116. RtcEngine = null;
  117. }
  118. }
  119. private void PushAudioFrameThread()
  120. {
  121. var bytesPerSample = 2;
  122. var type = AUDIO_FRAME_TYPE.FRAME_TYPE_PCM16;
  123. var channels = CHANNEL;
  124. var samples = SAMPLE_RATE / PUSH_FREQ_PER_SEC;
  125. var samplesPerSec = SAMPLE_RATE;
  126. var buffer = new byte[samples * bytesPerSample * CHANNEL];
  127. var freq = 1000 / PUSH_FREQ_PER_SEC;
  128. var tic = DateTime.Now;
  129. IntPtr audioFrameBuffer = Marshal.AllocHGlobal(buffer.Length);
  130. var audioFrame = new AudioFrame
  131. {
  132. bytesPerSample = BYTES_PER_SAMPLE.TWO_BYTES_PER_SAMPLE,
  133. type = type,
  134. samplesPerChannel = samples,
  135. samplesPerSec = samplesPerSec,
  136. channels = channels,
  137. buffer = (UInt64)audioFrameBuffer,
  138. bufferPtr = audioFrameBuffer,
  139. RawBuffer = buffer,
  140. renderTimeMs = freq
  141. };
  142. while (true)
  143. {
  144. lock (_pushAudioFrameThreadSignal)
  145. {
  146. if (RtcEngine == null)
  147. {
  148. break;
  149. }
  150. var toc = DateTime.Now;
  151. if ((toc - tic).Milliseconds >= freq)
  152. {
  153. lock (_audioBuffer)
  154. {
  155. if (_audioBuffer.Size > samples * bytesPerSample * CHANNEL)
  156. {
  157. for (var j = 0; j < samples * bytesPerSample * CHANNEL; j++)
  158. {
  159. buffer[j] = _audioBuffer.Get();
  160. }
  161. Marshal.Copy(buffer, 0, audioFrame.bufferPtr, buffer.Length);
  162. var ret = RtcEngine.PushAudioFrame(MEDIA_SOURCE_TYPE.AUDIO_PLAYOUT_SOURCE, audioFrame);
  163. Debug.Log("PushAudioFrame returns: " + ret);
  164. tic = toc;
  165. }
  166. else
  167. {
  168. tic = tic.AddMilliseconds(1);
  169. }
  170. }
  171. }
  172. }
  173. Thread.Sleep(1);
  174. }
  175. Marshal.FreeHGlobal(audioFrameBuffer);
  176. }
  177. private void OnAudioFilterRead(float[] data, int channels)
  178. {
  179. if (!_startConvertSignal) return;
  180. var rescaleFactor = 32767;
  181. foreach (var t in data)
  182. {
  183. var sample = t;
  184. if (sample > 1) sample = 1;
  185. else if (sample < -1) sample = -1;
  186. var shortData = (short)(sample * rescaleFactor);
  187. var byteArr = new byte[2];
  188. byteArr = BitConverter.GetBytes(shortData);
  189. lock (_audioBuffer)
  190. {
  191. _audioBuffer.Put(byteArr[0]);
  192. _audioBuffer.Put(byteArr[1]);
  193. }
  194. }
  195. //_count += 1;
  196. //if (_count == 20) _startSignal = true;
  197. }
  198. }
  199. #region -- Agora Event ---
  200. internal class UserEventHandler : IRtcEngineEventHandler
  201. {
  202. private readonly CustomCaptureAudio _customAudioSource;
  203. internal UserEventHandler(CustomCaptureAudio customAudioSource)
  204. {
  205. _customAudioSource = customAudioSource;
  206. }
  207. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  208. {
  209. int build = 0;
  210. _customAudioSource.Log.UpdateLog(string.Format("sdk version: {0}",
  211. _customAudioSource.RtcEngine.GetVersion(ref build)));
  212. _customAudioSource.Log.UpdateLog(string.Format(
  213. "onJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}", connection.channelId,
  214. connection.localUid, elapsed));
  215. }
  216. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  217. {
  218. _customAudioSource.Log.UpdateLog("OnLeaveChannelSuccess");
  219. }
  220. public override void OnError(int error, string msg)
  221. {
  222. _customAudioSource.Log.UpdateLog(string.Format("OnSDKError error: {0}, msg: {1}", error, msg));
  223. }
  224. public override void OnConnectionLost(RtcConnection connection)
  225. {
  226. _customAudioSource.Log.UpdateLog(string.Format("OnConnectionLost "));
  227. }
  228. }
  229. #endregion
  230. }