ProcessAudioRawData.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. using UnityEngine.Serialization;
  5. using Agora.Rtc;
  6. using Agora.Util;
  7. using Logger = Agora.Util.Logger;
  8. using RingBuffer;
  9. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.ProcessAudioRawData
  10. {
  11. public class ProcessAudioRawData : MonoBehaviour
  12. {
  13. [FormerlySerializedAs("appIdInput")]
  14. [SerializeField]
  15. private AppIdInput _appIdInput;
  16. [Header("_____________Basic Configuration_____________")]
  17. [FormerlySerializedAs("APP_ID")]
  18. [SerializeField]
  19. private string _appID = "";
  20. [FormerlySerializedAs("TOKEN")]
  21. [SerializeField]
  22. private string _token = "";
  23. [FormerlySerializedAs("CHANNEL_NAME")]
  24. [SerializeField]
  25. private string _channelName = "";
  26. public Text LogText;
  27. internal Logger Log;
  28. internal IRtcEngine RtcEngine;
  29. private const int CHANNEL = 1;
  30. private const int PULL_FREQ_PER_SEC = 100;
  31. public const int SAMPLE_RATE = 32000; // this should = CLIP_SAMPLES x PULL_FREQ_PER_SEC
  32. public const int CLIP_SAMPLES = 320;
  33. internal int _count;
  34. internal int _writeCount;
  35. internal int _readCount;
  36. internal RingBuffer<float> _audioBuffer;
  37. internal AudioClip _audioClip;
  38. private bool _startSignal;
  39. void Start()
  40. {
  41. LoadAssetData();
  42. if (CheckAppId())
  43. {
  44. InitEngine();
  45. JoinChannel();
  46. var aud = GetComponent<AudioSource>();
  47. if (aud == null)
  48. {
  49. gameObject.AddComponent<AudioSource>();
  50. }
  51. SetupAudio(aud, "externalClip");
  52. }
  53. }
  54. // Update is called once per frame
  55. void Update()
  56. {
  57. PermissionHelper.RequestMicrophontPermission();
  58. PermissionHelper.RequestCameraPermission();
  59. }
  60. bool CheckAppId()
  61. {
  62. Log = new Logger(LogText);
  63. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  64. }
  65. //Show data in AgoraBasicProfile
  66. [ContextMenu("ShowAgoraBasicProfileData")]
  67. public void LoadAssetData()
  68. {
  69. if (_appIdInput == null) return;
  70. _appID = _appIdInput.appID;
  71. _token = _appIdInput.token;
  72. _channelName = _appIdInput.channelName;
  73. }
  74. void InitEngine()
  75. {
  76. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  77. UserEventHandler handler = new UserEventHandler(this);
  78. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  79. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  80. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  81. RtcEngine.Initialize(context);
  82. RtcEngine.InitEventHandler(handler);
  83. RtcEngine.RegisterAudioFrameObserver(new AudioFrameObserver(this), OBSERVER_MODE.RAW_DATA);
  84. RtcEngine.SetPlaybackAudioFrameParameters(SAMPLE_RATE, 1, RAW_AUDIO_FRAME_OP_MODE_TYPE.RAW_AUDIO_FRAME_OP_MODE_READ_ONLY, 1024);
  85. }
  86. void JoinChannel()
  87. {
  88. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  89. RtcEngine.EnableAudio();
  90. RtcEngine.EnableVideo();
  91. RtcEngine.JoinChannel(_token, _channelName, "");
  92. }
  93. private void OnDestroy()
  94. {
  95. Debug.Log("OnDestroy");
  96. if (RtcEngine != null)
  97. {
  98. RtcEngine.UnRegisterAudioFrameObserver();
  99. RtcEngine.InitEventHandler(null);
  100. RtcEngine.LeaveChannel();
  101. RtcEngine.Dispose();
  102. }
  103. }
  104. void SetupAudio(AudioSource aud, string clipName)
  105. {
  106. // //The larger the buffer, the higher the delay
  107. var bufferLength = SAMPLE_RATE / PULL_FREQ_PER_SEC * CHANNEL * 100; // 1-sec-length buffer
  108. _audioBuffer = new RingBuffer<float>(bufferLength, true);
  109. _audioClip = AudioClip.Create(clipName,
  110. CLIP_SAMPLES,
  111. CHANNEL, SAMPLE_RATE, true,
  112. OnAudioRead);
  113. aud.clip = _audioClip;
  114. aud.loop = true;
  115. aud.Play();
  116. }
  117. private void OnAudioRead(float[] data)
  118. {
  119. for (var i = 0; i < data.Length; i++)
  120. {
  121. lock (_audioBuffer)
  122. {
  123. if (_audioBuffer.Count > 0)
  124. {
  125. data[i] = _audioBuffer.Get();
  126. _readCount += 1;
  127. }
  128. }
  129. }
  130. Debug.LogFormat("buffer length remains: {0}", _writeCount - _readCount);
  131. }
  132. internal static float[] ConvertByteToFloat16(byte[] byteArray)
  133. {
  134. var floatArray = new float[byteArray.Length / 2];
  135. for (var i = 0; i < floatArray.Length; i++)
  136. {
  137. floatArray[i] = BitConverter.ToInt16(byteArray, i * 2) / 32768f; // -Int16.MinValue
  138. }
  139. return floatArray;
  140. }
  141. }
  142. #region -- Agora Event ---
  143. internal class UserEventHandler : IRtcEngineEventHandler
  144. {
  145. private readonly ProcessAudioRawData _agoraVideoRawData;
  146. internal UserEventHandler(ProcessAudioRawData agoraVideoRawData)
  147. {
  148. _agoraVideoRawData = agoraVideoRawData;
  149. }
  150. public override void OnError(int err, string msg)
  151. {
  152. _agoraVideoRawData.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  153. }
  154. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  155. {
  156. int build = 0;
  157. _agoraVideoRawData.Log.UpdateLog(string.Format("sdk version: ${0}",
  158. _agoraVideoRawData.RtcEngine.GetVersion(ref build)));
  159. _agoraVideoRawData.Log.UpdateLog(
  160. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  161. connection.channelId, connection.localUid, elapsed));
  162. }
  163. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  164. {
  165. _agoraVideoRawData.Log.UpdateLog("OnRejoinChannelSuccess");
  166. }
  167. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  168. {
  169. _agoraVideoRawData.Log.UpdateLog("OnLeaveChannel");
  170. }
  171. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole,
  172. CLIENT_ROLE_TYPE newRole)
  173. {
  174. _agoraVideoRawData.Log.UpdateLog("OnClientRoleChanged");
  175. }
  176. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  177. {
  178. _agoraVideoRawData.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid,
  179. elapsed));
  180. }
  181. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  182. {
  183. _agoraVideoRawData.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  184. (int)reason));
  185. }
  186. }
  187. internal class AudioFrameObserver : IAudioFrameObserver
  188. {
  189. private readonly ProcessAudioRawData _agoraAudioRawData;
  190. private AudioParams _audioParams;
  191. internal AudioFrameObserver(ProcessAudioRawData agoraAudioRawData)
  192. {
  193. _agoraAudioRawData = agoraAudioRawData;
  194. _audioParams = new AudioParams();
  195. _audioParams.sample_rate = 16000;
  196. _audioParams.channels = 2;
  197. _audioParams.mode = RAW_AUDIO_FRAME_OP_MODE_TYPE.RAW_AUDIO_FRAME_OP_MODE_READ_ONLY;
  198. _audioParams.samples_per_call = 1024;
  199. }
  200. public override bool OnRecordAudioFrame(string channelId, AudioFrame audioFrame)
  201. {
  202. Debug.Log("OnRecordAudioFrame-----------");
  203. return true;
  204. }
  205. public override bool OnPlaybackAudioFrame(string channelId, AudioFrame audioFrame)
  206. {
  207. Debug.Log("OnPlaybackAudioFrame-----------");
  208. if (_agoraAudioRawData._count == 1)
  209. {
  210. Debug.LogWarning("audioFrame = " + audioFrame);
  211. }
  212. var floatArray = ProcessAudioRawData.ConvertByteToFloat16(audioFrame.RawBuffer);
  213. lock (_agoraAudioRawData._audioBuffer)
  214. {
  215. _agoraAudioRawData._audioBuffer.Put(floatArray);
  216. _agoraAudioRawData._writeCount += floatArray.Length;
  217. _agoraAudioRawData._count++;
  218. }
  219. return true;
  220. }
  221. public override int GetObservedAudioFramePosition()
  222. {
  223. Debug.Log("GetObservedAudioFramePosition-----------");
  224. return (int)(AUDIO_FRAME_POSITION.AUDIO_FRAME_POSITION_PLAYBACK |
  225. AUDIO_FRAME_POSITION.AUDIO_FRAME_POSITION_RECORD |
  226. AUDIO_FRAME_POSITION.AUDIO_FRAME_POSITION_BEFORE_MIXING |
  227. AUDIO_FRAME_POSITION.AUDIO_FRAME_POSITION_MIXED);
  228. }
  229. public override AudioParams GetPlaybackAudioParams()
  230. {
  231. Debug.Log("GetPlaybackAudioParams-----------");
  232. return this._audioParams;
  233. }
  234. public override AudioParams GetRecordAudioParams()
  235. {
  236. Debug.Log("GetRecordAudioParams-----------");
  237. return this._audioParams;
  238. }
  239. public override AudioParams GetMixedAudioParams()
  240. {
  241. Debug.Log("GetMixedAudioParams-----------");
  242. return this._audioParams;
  243. }
  244. public override bool OnPlaybackAudioFrameBeforeMixing(string channel_id,
  245. uint uid,
  246. AudioFrame audio_frame)
  247. {
  248. Debug.Log("OnPlaybackAudioFrameBeforeMixing-----------");
  249. return false;
  250. }
  251. public override bool OnPlaybackAudioFrameBeforeMixing(string channel_id,
  252. string uid,
  253. AudioFrame audio_frame)
  254. {
  255. Debug.Log("OnPlaybackAudioFrameBeforeMixing2-----------");
  256. return false;
  257. }
  258. }
  259. #endregion
  260. }