SpatialAudioWithMediaPlayer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.SpatialAudioWithMediaPlayer
  9. {
  10. public class SpatialAudioWithMediaPlayer : MonoBehaviour
  11. {
  12. [FormerlySerializedAs("appIdInput")]
  13. [SerializeField]
  14. private AppIdInput _appIdInput;
  15. [Header("_____________Basic Configuration_____________")]
  16. [FormerlySerializedAs("APP_ID")]
  17. [SerializeField]
  18. private string _appID = "";
  19. [FormerlySerializedAs("TOKEN")]
  20. [SerializeField]
  21. private string _token = "";
  22. [FormerlySerializedAs("CHANNEL_NAME")]
  23. [SerializeField]
  24. private string _channelName = "";
  25. public Text LogText;
  26. internal Logger Log;
  27. internal IRtcEngineEx RtcEngine = null;
  28. internal IMediaPlayer MediaPlayer = null;
  29. private const string MPK_URL =
  30. "https://agoracdn.s3.us-west-1.amazonaws.com/videos/Agora.io-Interactions.mp4";
  31. private Button _button1;
  32. private Button _button2;
  33. private Button _button3;
  34. public uint UidUseInEx = 123;
  35. public uint UidUseInMPK = 67890;
  36. public ILocalSpatialAudioEngine SpatialAudioEngine;
  37. public int x = 0;
  38. // Use this for initialization
  39. private void Start()
  40. {
  41. LoadAssetData();
  42. if (CheckAppId())
  43. {
  44. SetUpUI();
  45. InitEngine();
  46. InitMediaPlayer();
  47. InitSpatialAudioEngine();
  48. JoinChannelEx(_channelName, UidUseInEx);
  49. JoinChannelExWithMPK(_channelName, UidUseInMPK, MediaPlayer.GetId());
  50. }
  51. }
  52. // Update is called once per frame
  53. private void Update()
  54. {
  55. PermissionHelper.RequestMicrophontPermission();
  56. PermissionHelper.RequestCameraPermission();
  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 InitEngine()
  73. {
  74. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngineEx();
  75. UserEventHandler handler = new UserEventHandler(this);
  76. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  77. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  78. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
  79. var ret = RtcEngine.Initialize(context);
  80. Debug.Log("Agora: Initialize " + ret);
  81. RtcEngine.InitEventHandler(handler);
  82. }
  83. private void InitMediaPlayer()
  84. {
  85. MediaPlayer = RtcEngine.CreateMediaPlayer();
  86. if (MediaPlayer == null)
  87. {
  88. Debug.Log("GetAgoraRtcMediaPlayer failed!");
  89. return;
  90. }
  91. MpkEventHandler handler = new MpkEventHandler(this);
  92. MediaPlayer.InitEventHandler(handler);
  93. Debug.Log("playerId id: " + MediaPlayer.GetId());
  94. }
  95. private void InitSpatialAudioEngine()
  96. {
  97. SpatialAudioEngine = RtcEngine.GetLocalSpatialAudioEngine();
  98. var ret = SpatialAudioEngine.Initialize();
  99. Debug.Log("_spatialAudioEngine: Initialize " + ret);
  100. SpatialAudioEngine.SetAudioRecvRange(30);
  101. }
  102. private void JoinChannelEx(string channelName, uint uid)
  103. {
  104. RtcEngine.EnableAudio();
  105. RtcEngine.EnableVideo();
  106. RtcEngine.EnableSpatialAudio(true);
  107. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  108. RtcConnection connection = new RtcConnection();
  109. connection.channelId = channelName;
  110. connection.localUid = uid;
  111. ChannelMediaOptions options = new ChannelMediaOptions();
  112. options.autoSubscribeAudio.SetValue(true);
  113. options.autoSubscribeVideo.SetValue(true);
  114. options.publishMicrophoneTrack.SetValue(false);
  115. options.publishCameraTrack.SetValue(true);
  116. options.enableAudioRecordingOrPlayout.SetValue(true);
  117. options.clientRoleType.SetValue(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  118. var ret = RtcEngine.JoinChannelEx("", connection, options);
  119. Debug.Log("RtcEngineController JoinChannelEx returns: " + ret);
  120. }
  121. private void JoinChannelExWithMPK(string channelName, uint uid, int playerId)
  122. {
  123. RtcConnection connection = new RtcConnection();
  124. connection.channelId = channelName;
  125. connection.localUid = uid;
  126. ChannelMediaOptions options = new ChannelMediaOptions();
  127. options.autoSubscribeAudio.SetValue(false);
  128. options.autoSubscribeVideo.SetValue(true);
  129. //options.publishAudioTrack.SetValue(false);
  130. options.publishCameraTrack.SetValue(false);
  131. options.publishMediaPlayerAudioTrack.SetValue(true);
  132. options.publishMediaPlayerVideoTrack.SetValue(true);
  133. options.publishMediaPlayerId.SetValue(playerId);
  134. options.enableAudioRecordingOrPlayout.SetValue(false);
  135. options.clientRoleType.SetValue(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  136. var ret = RtcEngine.JoinChannelEx("", connection, options);
  137. RtcEngine.UpdateChannelMediaOptionsEx(options, connection);
  138. Debug.Log("RtcEngineController JoinChannelEx_MPK returns: " + ret);
  139. }
  140. private void SetUpUI()
  141. {
  142. _button1 = GameObject.Find("Button1").GetComponent<Button>();
  143. _button1.onClick.AddListener(onLeftLocationPress);
  144. _button2 = GameObject.Find("Button2").GetComponent<Button>();
  145. _button2.onClick.AddListener(onRightLocationPress);
  146. _button3 = GameObject.Find("Button3").GetComponent<Button>();
  147. _button3.onClick.AddListener(onOpenButtonPress);
  148. }
  149. private void onLeftLocationPress()
  150. {
  151. float[] f1 = { 0.0f, 1.0f, 0.0f };
  152. var ret = SpatialAudioEngine.UpdateRemotePositionEx(UidUseInMPK, f1, new float[] { 0, 0, 0 }, new RtcConnection(_channelName, UidUseInEx));
  153. Debug.Log("_spatialAudio.UpdateRemotePosition returns: " + ret);
  154. }
  155. private void onRightLocationPress()
  156. {
  157. float[] f1 = { 0.0f, -1.0f, 0.0f };
  158. var ret = SpatialAudioEngine.UpdateRemotePositionEx(UidUseInMPK, f1, new float[] { 0, 0, 0 }, new RtcConnection(_channelName, UidUseInEx));
  159. Debug.Log("_spatialAudio.UpdateRemotePosition returns: " + ret);
  160. }
  161. private void onOpenButtonPress()
  162. {
  163. var ret = MediaPlayer.Open(MPK_URL, 0);
  164. Debug.Log("_mediaPlayer.Open returns: " + ret);
  165. MediaPlayer.AdjustPlayoutVolume(0);
  166. }
  167. private void OnDestroy()
  168. {
  169. Debug.Log("OnDestroy");
  170. if (RtcEngine == null) return;
  171. RtcEngine.InitEventHandler(null);
  172. RtcEngine.LeaveChannel();
  173. RtcEngine.Dispose();
  174. }
  175. internal string GetChannelName()
  176. {
  177. return _channelName;
  178. }
  179. #region -- Video Render UI Logic ---
  180. internal static void MakeVideoView(uint uid, string channelId = "", VIDEO_SOURCE_TYPE source = VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE)
  181. {
  182. var go = GameObject.Find(uid.ToString());
  183. if (!ReferenceEquals(go, null))
  184. {
  185. return; // reuse
  186. }
  187. // create a GameObject and assign to this new user
  188. var videoSurface = MakeImageSurface(uid.ToString());
  189. if (ReferenceEquals(videoSurface, null)) return;
  190. // configure videoSurface
  191. videoSurface.SetForUser(uid, channelId, source);
  192. videoSurface.SetEnable(true);
  193. videoSurface.OnTextureSizeModify += (int width, int height) =>
  194. {
  195. float scale = (float)height / (float)width;
  196. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  197. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  198. };
  199. }
  200. // VIDEO TYPE 1: 3D Object
  201. private static VideoSurface MakePlaneSurface(string goName)
  202. {
  203. var go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  204. if (go == null)
  205. {
  206. return null;
  207. }
  208. go.name = goName;
  209. // set up transform
  210. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  211. go.transform.position = Vector3.zero;
  212. go.transform.localScale = new Vector3(0.25f, 0.5f, 0.5f);
  213. // configure videoSurface
  214. var videoSurface = go.AddComponent<VideoSurface>();
  215. return videoSurface;
  216. }
  217. // Video TYPE 2: RawImage
  218. private static VideoSurface MakeImageSurface(string goName)
  219. {
  220. GameObject go = new GameObject();
  221. if (go == null)
  222. {
  223. return null;
  224. }
  225. go.name = goName;
  226. // to be renderered onto
  227. go.AddComponent<RawImage>();
  228. // make the object draggable
  229. go.AddComponent<UIElementDrag>();
  230. var canvas = GameObject.Find("VideoCanvas");
  231. if (canvas != null)
  232. {
  233. go.transform.parent = canvas.transform;
  234. Debug.Log("add video view");
  235. }
  236. else
  237. {
  238. Debug.Log("Canvas is null video view");
  239. }
  240. // set up transform
  241. go.transform.Rotate(0f, 0.0f, 180.0f);
  242. go.transform.localPosition = Vector3.zero;
  243. go.transform.localScale = new Vector3(2f, 3f, 1f);
  244. // configure videoSurface
  245. var videoSurface = go.AddComponent<VideoSurface>();
  246. return videoSurface;
  247. }
  248. internal static void DestroyVideoView(uint uid)
  249. {
  250. var go = GameObject.Find(uid.ToString());
  251. if (!ReferenceEquals(go, null))
  252. {
  253. Destroy(go);
  254. }
  255. }
  256. #endregion
  257. }
  258. #region -- Agora Event ---
  259. internal class MpkEventHandler : IMediaPlayerSourceObserver
  260. {
  261. private readonly SpatialAudioWithMediaPlayer _spatialAudio;
  262. internal MpkEventHandler(SpatialAudioWithMediaPlayer spatialAudio)
  263. {
  264. _spatialAudio = spatialAudio;
  265. }
  266. public override void OnPlayerSourceStateChanged(MEDIA_PLAYER_STATE state, MEDIA_PLAYER_ERROR ec)
  267. {
  268. _spatialAudio.Log.UpdateLog(string.Format(
  269. "OnPlayerSourceStateChanged state: {0}, ec: {1}, playId: {2}", state, ec, _spatialAudio.MediaPlayer.GetId()));
  270. Debug.Log("OnPlayerSourceStateChanged");
  271. if (state == MEDIA_PLAYER_STATE.PLAYER_STATE_OPEN_COMPLETED)
  272. {
  273. _spatialAudio.x = 1;
  274. var ret = _spatialAudio.MediaPlayer.Play();
  275. Debug.Log("Play return" + ret);
  276. SpatialAudioWithMediaPlayer.MakeVideoView(_spatialAudio.UidUseInMPK, _spatialAudio.GetChannelName(), VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  277. }
  278. }
  279. }
  280. internal class UserEventHandler : IRtcEngineEventHandler
  281. {
  282. private readonly SpatialAudioWithMediaPlayer _spatialAudio;
  283. internal UserEventHandler(SpatialAudioWithMediaPlayer spatialAudio)
  284. {
  285. _spatialAudio = spatialAudio;
  286. }
  287. public override void OnError(int err, string msg)
  288. {
  289. _spatialAudio.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  290. }
  291. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  292. {
  293. Debug.Log("Agora: OnJoinChannelSuccess ");
  294. _spatialAudio.Log.UpdateLog(
  295. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  296. connection.channelId, connection.localUid, elapsed));
  297. float[] f1 = new float[] { 0.0f, 0.0f, 0.0f };
  298. float[] f2 = new float[] { 1.0f, 0.0f, 0.0f };
  299. float[] f3 = new float[] { 0.0f, 1.0f, 0.0f };
  300. float[] f4 = new float[] { 0.0f, 0.0f, 1.0f };
  301. var ret = _spatialAudio.SpatialAudioEngine.UpdateSelfPositionEx(f1, f2, f3, f4, connection);
  302. Debug.Log("UpdateSelfPosition return: " + ret);
  303. }
  304. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  305. {
  306. _spatialAudio.Log.UpdateLog("OnRejoinChannelSuccess");
  307. }
  308. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  309. {
  310. _spatialAudio.Log.UpdateLog("OnLeaveChannel");
  311. SpatialAudioWithMediaPlayer.DestroyVideoView(0);
  312. }
  313. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole, CLIENT_ROLE_TYPE newRole)
  314. {
  315. _spatialAudio.Log.UpdateLog("OnClientRoleChanged");
  316. }
  317. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  318. {
  319. _spatialAudio.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  320. if (uid == _spatialAudio.UidUseInMPK)
  321. {
  322. _spatialAudio.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  323. }
  324. else if (uid == _spatialAudio.UidUseInEx)
  325. {
  326. _spatialAudio.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  327. SpatialAudioWithMediaPlayer.MakeVideoView(uid, _spatialAudio.GetChannelName());
  328. }
  329. }
  330. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  331. {
  332. _spatialAudio.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  333. (int)reason));
  334. SpatialAudioWithMediaPlayer.DestroyVideoView(uid);
  335. }
  336. }
  337. #endregion
  338. }