CustomRenderAudio.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. using System;
  2. using System.Threading;
  3. using System.Runtime.InteropServices;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using UnityEngine.Serialization;
  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.CustomRenderAudio
  12. {
  13. public class CustomRenderAudio : 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;
  31. private const int CHANNEL = 1;
  32. private const int SAMPLE_RATE = 44100;
  33. private const int PULL_FREQ_PER_SEC = 100;
  34. private RingBuffer<float> _audioBuffer;
  35. private AudioClip _audioClip;
  36. private Thread _pullAudioFrameThread;
  37. private System.Object _pullAudioFrameThreadSignal = new System.Object();
  38. private int _writeCount;
  39. private int _readCount;
  40. private void Start()
  41. {
  42. LoadAssetData();
  43. if (CheckAppId())
  44. {
  45. InitRtcEngine();
  46. JoinChannel();
  47. var aud = InitAudioSource();
  48. StartPullAudioFrame(aud, "externalClip");
  49. }
  50. }
  51. private void Update()
  52. {
  53. PermissionHelper.RequestMicrophontPermission();
  54. }
  55. private bool CheckAppId()
  56. {
  57. Log = new Logger(LogText);
  58. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  59. }
  60. //Show data in AgoraBasicProfile
  61. [ContextMenu("ShowAgoraBasicProfileData")]
  62. private void LoadAssetData()
  63. {
  64. if (_appIdInput == null) return;
  65. _appID = _appIdInput.appID;
  66. _token = _appIdInput.token;
  67. _channelName = _appIdInput.channelName;
  68. }
  69. private void InitRtcEngine()
  70. {
  71. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  72. UserEventHandler handler = new UserEventHandler(this);
  73. //be care, enableAudioDevice need be false
  74. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  75. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  76. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  77. var ret = RtcEngine.Initialize(context);
  78. RtcEngine.InitEventHandler(handler);
  79. }
  80. private void JoinChannel()
  81. {
  82. RtcEngine.EnableAudio();
  83. //no enableAudioDevice to set false? how this methond work?
  84. var nRet = RtcEngine.SetExternalAudioSink(true,SAMPLE_RATE, CHANNEL);
  85. this.Log.UpdateLog("SetExternalAudioSink ret:" + nRet);
  86. RtcEngine.JoinChannel(_token, _channelName);
  87. }
  88. private AudioSource InitAudioSource()
  89. {
  90. var aud = GetComponent<AudioSource>();
  91. if (aud == null)
  92. {
  93. aud = gameObject.AddComponent<AudioSource>();
  94. }
  95. return aud;
  96. }
  97. private void StartPullAudioFrame(AudioSource aud, string clipName)
  98. {
  99. // 1-sec-length buffer
  100. var bufferLength = SAMPLE_RATE * CHANNEL;
  101. _audioBuffer = new RingBuffer<float>(bufferLength, true);
  102. _pullAudioFrameThread = new Thread(PullAudioFrameThread);
  103. _pullAudioFrameThread.Start();
  104. _audioClip = AudioClip.Create(clipName,
  105. SAMPLE_RATE / PULL_FREQ_PER_SEC * CHANNEL, CHANNEL, SAMPLE_RATE, true,
  106. OnAudioRead);
  107. aud.clip = _audioClip;
  108. aud.loop = true;
  109. aud.Play();
  110. }
  111. private void OnDestroy()
  112. {
  113. Debug.Log("OnDestroy");
  114. lock (_pullAudioFrameThreadSignal)
  115. {
  116. if (RtcEngine == null) return;
  117. RtcEngine.InitEventHandler(null);
  118. RtcEngine.LeaveChannel();
  119. RtcEngine.Dispose();
  120. RtcEngine = null;
  121. }
  122. }
  123. private void PullAudioFrameThread()
  124. {
  125. var avsync_type = 0;
  126. var bytesPerSample = 2;
  127. var type = AUDIO_FRAME_TYPE.FRAME_TYPE_PCM16;
  128. var channels = CHANNEL;
  129. var samples = SAMPLE_RATE / PULL_FREQ_PER_SEC * CHANNEL;
  130. var samplesPerSec = SAMPLE_RATE;
  131. var buffer = new byte[samples * bytesPerSample];
  132. var freq = 1000 / PULL_FREQ_PER_SEC;
  133. var tic = new TimeSpan(DateTime.Now.Ticks);
  134. AudioFrame audioFrame = new AudioFrame(type, samples, BYTES_PER_SAMPLE.TWO_BYTES_PER_SAMPLE, channels, samplesPerSec, buffer, 0, avsync_type);
  135. IntPtr audioFrameBuffer = Marshal.AllocHGlobal(samples * bytesPerSample * channels);
  136. audioFrame.buffer = (UInt64)audioFrameBuffer;
  137. audioFrame.bufferPtr = audioFrameBuffer;
  138. while (true)
  139. {
  140. lock (_pullAudioFrameThreadSignal)
  141. {
  142. if (RtcEngine == null)
  143. {
  144. break;
  145. }
  146. var toc = new TimeSpan(DateTime.Now.Ticks);
  147. if (toc.Subtract(tic).Duration().Milliseconds >= freq)
  148. {
  149. tic = new TimeSpan(DateTime.Now.Ticks);
  150. var ret = RtcEngine.PullAudioFrame(audioFrame);
  151. Debug.Log("PullAudioFrame returns: " + ret);
  152. if (ret == 0)
  153. {
  154. Marshal.Copy((IntPtr)audioFrame.buffer, audioFrame.RawBuffer, 0, audioFrame.RawBuffer.Length);
  155. var floatArray = ConvertByteToFloat16(audioFrame.RawBuffer);
  156. lock (_audioBuffer)
  157. {
  158. _audioBuffer.Put(floatArray);
  159. }
  160. _writeCount += floatArray.Length;
  161. }
  162. }
  163. }
  164. Thread.Sleep(1);
  165. }
  166. Marshal.FreeHGlobal(audioFrameBuffer);
  167. }
  168. private static float[] ConvertByteToFloat16(byte[] byteArray)
  169. {
  170. var floatArray = new float[byteArray.Length / 2];
  171. for (var i = 0; i < floatArray.Length; i++)
  172. {
  173. floatArray[i] = BitConverter.ToInt16(byteArray, i * 2) / 32768f; // -Int16.MinValue
  174. }
  175. return floatArray;
  176. }
  177. private void OnAudioRead(float[] data)
  178. {
  179. //if (!_startSignal) return;
  180. for (var i = 0; i < data.Length; i++)
  181. {
  182. lock (_audioBuffer)
  183. {
  184. if (_audioBuffer.Count > 0)
  185. {
  186. data[i] = _audioBuffer.Get();
  187. }
  188. else
  189. {
  190. break;
  191. }
  192. }
  193. //readCount += 1;
  194. }
  195. Debug.LogFormat("buffer length remains: {0}", _writeCount - _readCount);
  196. }
  197. }
  198. #region -- Agora Event ---
  199. internal class UserEventHandler : IRtcEngineEventHandler
  200. {
  201. private readonly CustomRenderAudio _customAudioSinkSample;
  202. internal UserEventHandler(CustomRenderAudio customAudioSinkSample)
  203. {
  204. _customAudioSinkSample = customAudioSinkSample;
  205. }
  206. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  207. {
  208. int build = 0;
  209. _customAudioSinkSample.Log.UpdateLog(string.Format("sdk version: {0}", _customAudioSinkSample.RtcEngine.GetVersion(ref build)));
  210. _customAudioSinkSample.Log.UpdateLog(string.Format("onJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}", connection.channelId,
  211. connection.localUid, elapsed));
  212. }
  213. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  214. {
  215. _customAudioSinkSample.Log.UpdateLog("OnLeaveChannelSuccess");
  216. }
  217. public override void OnError(int error, string msg)
  218. {
  219. _customAudioSinkSample.Log.UpdateLog(string.Format("OnSDKError error: {0}, msg: {1}", error, msg));
  220. }
  221. public override void OnConnectionLost(RtcConnection connection)
  222. {
  223. _customAudioSinkSample.Log.UpdateLog(string.Format("OnConnectionLost "));
  224. }
  225. }
  226. #endregion
  227. }