AudioSpectrum.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  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. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.AudioSpectrum
  11. {
  12. public class AudioSpectrum : MonoBehaviour
  13. {
  14. [FormerlySerializedAs("appIdInput")]
  15. [SerializeField]
  16. private AppIdInput _appIdInput;
  17. [Header("_____________Basic Configuration_____________")]
  18. [FormerlySerializedAs("APP_ID")]
  19. [SerializeField]
  20. private string _appID = "";
  21. [FormerlySerializedAs("TOKEN")]
  22. [SerializeField]
  23. private string _token = "";
  24. [FormerlySerializedAs("CHANNEL_NAME")]
  25. [SerializeField]
  26. private string _channelName = "";
  27. public Text LogText;
  28. public RectTransform spectrums;
  29. public List<float> data = new List<float>();
  30. internal Logger Log;
  31. internal IRtcEngine RtcEngine = null;
  32. internal IMediaPlayer MediaPlayer = null;
  33. private const string MPK_URL =
  34. "https://agoracdn.s3.us-west-1.amazonaws.com/videos/Agora.io-Interactions.mp4";
  35. private Button _button1;
  36. private Button _button2;
  37. private Button _button3;
  38. private Button _button4;
  39. private Button _button5;
  40. private Toggle _urlToggle;
  41. // Use this for initialization
  42. private void Start()
  43. {
  44. LoadAssetData();
  45. if (CheckAppId())
  46. {
  47. SetUpUI();
  48. EnableUI(false);
  49. InitEngine();
  50. InitMediaPlayer();
  51. JoinChannelWithMPK();
  52. }
  53. }
  54. // Update is called once per frame
  55. private void Update()
  56. {
  57. PermissionHelper.RequestMicrophontPermission();
  58. PermissionHelper.RequestCameraPermission();
  59. lock (data)
  60. {
  61. if (data.Count > 0)
  62. {
  63. for (var i = 0; i < this.data.Count; i++)
  64. {
  65. var height = (-data[i] + 1);
  66. if (height <= 1) height = 1;
  67. var child = (RectTransform)this.spectrums.GetChild(i);
  68. child.sizeDelta = new Vector2(15, height);
  69. }
  70. }
  71. data.Clear();
  72. }
  73. }
  74. private void SetUpUI()
  75. {
  76. _button1 = GameObject.Find("Button1").GetComponent<Button>();
  77. _button1.onClick.AddListener(OnPlayButtonPress);
  78. _button2 = GameObject.Find("Button2").GetComponent<Button>();
  79. _button2.onClick.AddListener(OnStopButtonPress);
  80. _button3 = GameObject.Find("Button3").GetComponent<Button>();
  81. _button3.onClick.AddListener(OnPauseButtonPress);
  82. _button4 = GameObject.Find("Button4").GetComponent<Button>();
  83. _button4.onClick.AddListener(OnResumeButtonPress);
  84. _button5 = GameObject.Find("Button5").GetComponent<Button>();
  85. _button5.onClick.AddListener(OnOpenButtonPress);
  86. _urlToggle = GameObject.Find("UrlToggle").GetComponent<Toggle>();
  87. }
  88. public void EnableUI(bool val)
  89. {
  90. var obj = this.transform.Find("Button1").gameObject;
  91. obj.SetActive(val);
  92. obj = this.transform.Find("Button2").gameObject;
  93. obj.SetActive(val);
  94. obj = this.transform.Find("Button3").gameObject;
  95. obj.SetActive(val);
  96. obj = this.transform.Find("Button4").gameObject;
  97. obj.SetActive(val);
  98. }
  99. private bool CheckAppId()
  100. {
  101. Log = new Logger(LogText);
  102. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  103. }
  104. //Show data in AgoraBasicProfile
  105. [ContextMenu("ShowAgoraBasicProfileData")]
  106. private void LoadAssetData()
  107. {
  108. if (_appIdInput == null) return;
  109. _appID = _appIdInput.appID;
  110. _token = _appIdInput.token;
  111. _channelName = _appIdInput.channelName;
  112. }
  113. private void InitEngine()
  114. {
  115. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  116. UserEventHandler handler = new UserEventHandler(this);
  117. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  118. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  119. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
  120. RtcEngine.Initialize(context);
  121. RtcEngine.InitEventHandler(handler);
  122. }
  123. private void InitMediaPlayer()
  124. {
  125. MediaPlayer = RtcEngine.CreateMediaPlayer();
  126. if (MediaPlayer == null)
  127. {
  128. this.Log.UpdateLog("CreateMediaPlayer failed!");
  129. return;
  130. }
  131. MpkEventHandler handler = new MpkEventHandler(this);
  132. MediaPlayer.InitEventHandler(handler);
  133. this.Log.UpdateLog("playerId id: " + MediaPlayer.GetId());
  134. MediaPlayer.RegisterMediaPlayerAudioSpectrumObserver(new UserAudioSpectrumObserver(this), 16);
  135. }
  136. private void JoinChannelWithMPK()
  137. {
  138. RtcEngine.EnableAudio();
  139. RtcEngine.EnableVideo();
  140. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  141. ChannelMediaOptions options = new ChannelMediaOptions();
  142. options.autoSubscribeAudio.SetValue(true);
  143. options.autoSubscribeVideo.SetValue(true);
  144. options.publishCustomAudioTrack.SetValue(false);
  145. options.publishCameraTrack.SetValue(false);
  146. options.publishMediaPlayerAudioTrack.SetValue(true);
  147. options.publishMediaPlayerVideoTrack.SetValue(true);
  148. options.publishMediaPlayerId.SetValue(MediaPlayer.GetId());
  149. options.enableAudioRecordingOrPlayout.SetValue(true);
  150. options.clientRoleType.SetValue(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  151. var ret = RtcEngine.JoinChannel(_token, _channelName, 0, options);
  152. this.Log.UpdateLog("RtcEngineController JoinChannel_MPK returns: " + ret);
  153. }
  154. private void OnPlayButtonPress()
  155. {
  156. var ret = MediaPlayer.Play();
  157. this.Log.UpdateLog("Play return" + ret);
  158. this.TestMediaPlayer();
  159. }
  160. private void OnStopButtonPress()
  161. {
  162. var ret = MediaPlayer.Stop();
  163. this.Log.UpdateLog("Stop return" + ret);
  164. }
  165. private void OnPauseButtonPress()
  166. {
  167. var ret = MediaPlayer.Pause();
  168. this.Log.UpdateLog("Pause return" + ret);
  169. }
  170. private void OnResumeButtonPress()
  171. {
  172. var ret = MediaPlayer.Resume();
  173. this.Log.UpdateLog("Resume returns: " + ret);
  174. }
  175. private void OnOpenButtonPress()
  176. {
  177. string path = null;
  178. if (this._urlToggle.isOn)
  179. {
  180. path = MPK_URL;
  181. }
  182. else
  183. {
  184. #if UNITY_ANDROID && !UNITY_EDITOR
  185. // On Android, the StreamingAssetPath is just accessed by /assets instead of Application.streamingAssetPath
  186. path = "/assets/img/MPK.mov";
  187. #else
  188. path = Path.Combine(Application.streamingAssetsPath, "img/MPK.mov");
  189. #endif
  190. }
  191. this.Log.UpdateLog("Is opening : " + path);
  192. var ret = MediaPlayer.Open(path, 0);
  193. this.Log.UpdateLog("Open returns: " + ret);
  194. }
  195. private void TestMediaPlayer()
  196. {
  197. long duration = 0;
  198. var ret = MediaPlayer.GetDuration(ref duration);
  199. Debug.Log("_mediaPlayer.GetDuration returns: " + ret + "duration: " + duration);
  200. long pos = 0;
  201. ret = MediaPlayer.GetPlayPosition(ref pos);
  202. Debug.Log("_mediaPlayer.GetPlayPosition returns: " + ret + "position: " + pos);
  203. Debug.Log("_mediaPlayer.GetState:" + MediaPlayer.GetState());
  204. bool mute = true;
  205. ret = MediaPlayer.GetMute(ref mute);
  206. Debug.Log("_mediaPlayer.GetMute returns: " + ret + "mute: " + mute);
  207. int volume = 0;
  208. ret = MediaPlayer.GetPlayoutVolume(ref volume);
  209. Debug.Log("_mediaPlayer.GetPlayoutVolume returns: " + ret + "volume: " + volume);
  210. Debug.Log("SDK Version:" + MediaPlayer.GetPlayerSdkVersion());
  211. Debug.Log("GetPlaySrc:" + MediaPlayer.GetPlaySrc());
  212. }
  213. private void OnDestroy()
  214. {
  215. Debug.Log("OnDestroy");
  216. if (RtcEngine == null) return;
  217. if (MediaPlayer != null)
  218. RtcEngine.DestroyMediaPlayer(MediaPlayer);
  219. RtcEngine.InitEventHandler(null);
  220. RtcEngine.LeaveChannel();
  221. RtcEngine.Dispose();
  222. RtcEngine = null;
  223. }
  224. internal string GetChannelName()
  225. {
  226. return _channelName;
  227. }
  228. #region -- Video Render UI Logic ---
  229. internal static void MakeVideoView(uint uid, string channelId = "", VIDEO_SOURCE_TYPE videoSourceType = VIDEO_SOURCE_TYPE.VIDEO_SOURCE_CAMERA)
  230. {
  231. var go = GameObject.Find(uid.ToString());
  232. if (!ReferenceEquals(go, null))
  233. {
  234. return; // reuse
  235. }
  236. // create a GameObject and assign to this new user
  237. var videoSurface = MakeImageSurface(uid.ToString());
  238. if (ReferenceEquals(videoSurface, null)) return;
  239. // configure videoSurface
  240. videoSurface.SetForUser(uid, channelId, videoSourceType);
  241. videoSurface.SetEnable(true);
  242. videoSurface.OnTextureSizeModify += (int width, int height) =>
  243. {
  244. float scale = (float)height / (float)width;
  245. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  246. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  247. };
  248. }
  249. // VIDEO TYPE 1: 3D Object
  250. private VideoSurface MakePlaneSurface(string goName)
  251. {
  252. var go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  253. if (go == null)
  254. {
  255. return null;
  256. }
  257. go.name = goName;
  258. // set up transform
  259. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  260. go.transform.position = Vector3.zero;
  261. go.transform.localScale = new Vector3(1.0f, 1.333f, 0.5f);
  262. // configure videoSurface
  263. var videoSurface = go.AddComponent<VideoSurface>();
  264. return videoSurface;
  265. }
  266. // Video TYPE 2: RawImage
  267. private static VideoSurface MakeImageSurface(string goName)
  268. {
  269. GameObject go = new GameObject();
  270. if (go == null)
  271. {
  272. return null;
  273. }
  274. go.name = goName;
  275. // to be renderered onto
  276. go.AddComponent<RawImage>();
  277. // make the object draggable
  278. go.AddComponent<UIElementDrag>();
  279. var canvas = GameObject.Find("VideoCanvas");
  280. if (canvas != null)
  281. {
  282. go.transform.parent = canvas.transform;
  283. Debug.Log("add video view");
  284. }
  285. else
  286. {
  287. Debug.Log("Canvas is null video view");
  288. }
  289. // set up transform
  290. go.transform.Rotate(0f, 0.0f, 180.0f);
  291. go.transform.localPosition = Vector3.zero;
  292. go.transform.localScale = new Vector3(4.5f, 3f, 1f);
  293. // configure videoSurface
  294. var videoSurface = go.AddComponent<VideoSurface>();
  295. return videoSurface;
  296. }
  297. internal static void DestroyVideoView(uint uid)
  298. {
  299. var go = GameObject.Find(uid.ToString());
  300. if (!ReferenceEquals(go, null))
  301. {
  302. Destroy(go);
  303. }
  304. }
  305. #endregion
  306. }
  307. #region -- Agora Event ---
  308. internal class MpkEventHandler : IMediaPlayerSourceObserver
  309. {
  310. private readonly AudioSpectrum _sample;
  311. internal MpkEventHandler(AudioSpectrum sample)
  312. {
  313. _sample = sample;
  314. }
  315. public override void OnPlayerSourceStateChanged(MEDIA_PLAYER_STATE state, MEDIA_PLAYER_ERROR ec)
  316. {
  317. _sample.Log.UpdateLog(string.Format(
  318. "OnPlayerSourceStateChanged state: {0}, ec: {1}, playId: {2}", state, ec, _sample.MediaPlayer.GetId()));
  319. Debug.Log("OnPlayerSourceStateChanged");
  320. if (state == MEDIA_PLAYER_STATE.PLAYER_STATE_OPEN_COMPLETED)
  321. {
  322. AudioSpectrum.MakeVideoView((uint)_sample.MediaPlayer.GetId(), "", VIDEO_SOURCE_TYPE.VIDEO_SOURCE_MEDIA_PLAYER);
  323. _sample.EnableUI(true);
  324. _sample.Log.UpdateLog("Open Complete. Click start to play media");
  325. }
  326. else if (state == MEDIA_PLAYER_STATE.PLAYER_STATE_STOPPED)
  327. {
  328. AudioSpectrum.DestroyVideoView((uint)_sample.MediaPlayer.GetId());
  329. _sample.EnableUI(false);
  330. }
  331. }
  332. public override void OnPlayerEvent(MEDIA_PLAYER_EVENT @event, Int64 elapsedTime, string message)
  333. {
  334. _sample.Log.UpdateLog(string.Format("OnPlayerEvent state: {0}", @event));
  335. }
  336. }
  337. internal class UserEventHandler : IRtcEngineEventHandler
  338. {
  339. private readonly AudioSpectrum _sample;
  340. internal UserEventHandler(AudioSpectrum sample)
  341. {
  342. _sample = sample;
  343. }
  344. public override void OnError(int err, string msg)
  345. {
  346. _sample.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  347. }
  348. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  349. {
  350. int build = 0;
  351. _sample.Log.UpdateLog(string.Format("sdk version: ${0}",
  352. _sample.RtcEngine.GetVersion(ref build)));
  353. _sample.Log.UpdateLog(
  354. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  355. connection.channelId, connection.localUid, elapsed));
  356. }
  357. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  358. {
  359. _sample.Log.UpdateLog("OnRejoinChannelSuccess");
  360. }
  361. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  362. {
  363. _sample.Log.UpdateLog("OnLeaveChannel");
  364. AudioSpectrum.DestroyVideoView(0);
  365. }
  366. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole,
  367. CLIENT_ROLE_TYPE newRole)
  368. {
  369. _sample.Log.UpdateLog("OnClientRoleChanged");
  370. }
  371. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  372. {
  373. _sample.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  374. }
  375. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  376. {
  377. _sample.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  378. (int)reason));
  379. AudioSpectrum.DestroyVideoView(uid);
  380. }
  381. }
  382. internal class UserPlayerCustomDataProvider : IMediaPlayerCustomDataProvider
  383. {
  384. AudioSpectrum _sample;
  385. internal UserPlayerCustomDataProvider(AudioSpectrum sample)
  386. {
  387. _sample = sample;
  388. }
  389. public override Int64 OnSeek(Int64 offset, int whence)
  390. {
  391. Debug.Log("UserPlayerCustomDataProvider OnSeek");
  392. return 0;
  393. }
  394. public override int OnReadData(IntPtr bufferPtr, int bufferSize)
  395. {
  396. Debug.Log("UserPlayerCustomDataProvider OnReadData");
  397. return 0;
  398. }
  399. }
  400. internal class UserAudioSpectrumObserver : IAudioSpectrumObserver
  401. {
  402. AudioSpectrum _sample;
  403. bool s = true;
  404. internal UserAudioSpectrumObserver(AudioSpectrum sample)
  405. {
  406. this._sample = sample;
  407. }
  408. public override bool OnLocalAudioSpectrum(AudioSpectrumData data)
  409. {
  410. if (data.dataLength > 0)
  411. {
  412. lock (this._sample.data)
  413. {
  414. this._sample.data.Clear();
  415. var interval = (int)(data.dataLength / 15);
  416. for (var i = 0; i < 15; i++)
  417. {
  418. this._sample.data.Add(data.audioSpectrumData[i * interval]);
  419. }
  420. }
  421. }
  422. return true;
  423. }
  424. public override bool OnRemoteAudioSpectrum(UserAudioSpectrumInfo[] spectrums, uint spectrumNumber)
  425. {
  426. return true;
  427. }
  428. }
  429. #endregion
  430. }