AgoraTestVideoNotToken.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.Serialization;
  4. using Agora.Rtc;
  5. using Agora.Util;
  6. using Logger = Agora.Util.Logger;
  7. using System.Collections.Generic;
  8. public class AgoraTestVideoNotToken : MonoBehaviour
  9. {
  10. [FormerlySerializedAs("appIdInput")]
  11. [SerializeField]
  12. private AppIdInput _appIdInput;
  13. [Header("_____________Basic Configuration_____________")]
  14. [FormerlySerializedAs("APP_ID")]
  15. [SerializeField]
  16. private string _appID = "";
  17. [FormerlySerializedAs("TOKEN")]
  18. [SerializeField]
  19. private string _token = "";
  20. [FormerlySerializedAs("CHANNEL_NAME")]
  21. [SerializeField]
  22. private string _channelName = "";
  23. public Text LogText;
  24. internal Logger Log;
  25. internal IRtcEngine RtcEngine = null;
  26. private Button _stopPublishButton;
  27. public Button _startPublishButton;
  28. public InputField inputChannel;
  29. public Button joinChannel;
  30. public Button leaveChannel;
  31. public Button audioBtn;
  32. public Button videoBtn;
  33. private bool isAudio;
  34. private bool isVideo;
  35. private static Dictionary<string, Agora.Rtc.UserInfo> disUserPeer_Uid;
  36. // Use this for initialization
  37. private void Start()
  38. {
  39. LoadAssetData();
  40. if (CheckAppId())
  41. {
  42. InitEngine();
  43. // JoinChannel();
  44. SetupUI();
  45. }
  46. disUserPeer_Uid = new Dictionary<string, Agora.Rtc.UserInfo>();
  47. }
  48. // Update is called once per frame
  49. private void Update()
  50. {
  51. PermissionHelper.RequestMicrophontPermission();
  52. PermissionHelper.RequestCameraPermission();
  53. }
  54. //Show data in AgoraBasicProfile
  55. [ContextMenu("ShowAgoraBasicProfileData")]
  56. private void LoadAssetData()
  57. {
  58. if (_appIdInput == null) return;
  59. _appID = _appIdInput.appID;
  60. _token = _appIdInput.token;
  61. _channelName = _appIdInput.channelName;
  62. }
  63. private bool CheckAppId()
  64. {
  65. Log = new Logger(LogText);
  66. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  67. }
  68. private void InitEngine()
  69. {
  70. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  71. AgoraVideoTestEventHandler handler = new AgoraVideoTestEventHandler(this);
  72. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  73. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  74. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  75. RtcEngine.Initialize(context);
  76. RtcEngine.InitEventHandler(handler);
  77. }
  78. private void JoinChannel()
  79. {
  80. RtcEngine.EnableAudio();
  81. RtcEngine.EnableVideo();
  82. VideoEncoderConfiguration config = new VideoEncoderConfiguration();
  83. config.dimensions = new VideoDimensions(640, 360);
  84. config.frameRate = 15;
  85. config.bitrate = 0;
  86. RtcEngine.SetVideoEncoderConfiguration(config);
  87. RtcEngine.SetChannelProfile(CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_COMMUNICATION);
  88. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  89. _channelName = inputChannel.text;
  90. RtcEngine.JoinChannel(_token, _channelName);
  91. }
  92. private void SetupUI()
  93. {
  94. _stopPublishButton = GameObject.Find("StopButton").GetComponent<Button>();
  95. _stopPublishButton.onClick.AddListener(StopPublish);
  96. _startPublishButton = GameObject.Find("StartButton").GetComponent<Button>();
  97. _startPublishButton.onClick.AddListener(StartPublish);
  98. _startPublishButton.gameObject.SetActive(false);
  99. joinChannel.onClick.AddListener(JoinChannel);
  100. leaveChannel.onClick.AddListener(LeaveChannel);
  101. isAudio = true;
  102. isVideo = true;
  103. audioBtn.onClick.AddListener(() =>
  104. {
  105. isAudio = !isAudio;
  106. int msg = RtcEngine.EnableLocalAudio(isAudio);
  107. switch (msg)
  108. {
  109. case 0:
  110. LogText.text = isAudio?"打开本地音频成功":"关闭本地音频成功 ";
  111. break;
  112. default:
  113. LogText.text = "开关本地音频失败: " + msg;
  114. break;
  115. }
  116. });
  117. videoBtn.onClick.AddListener(() =>
  118. {
  119. isVideo = !isVideo;
  120. int msg = RtcEngine.EnableLocalVideo(isVideo);
  121. switch (msg)
  122. {
  123. case 0:
  124. LogText.text = isVideo?"打开本地视频成功 ": "关闭本地视频成功 ";
  125. break;
  126. default:
  127. LogText.text = "开关本地视频失败: " + msg;
  128. break;
  129. }
  130. });
  131. //取消或恢复订阅指定远端用户的音频流。
  132. //RtcEngine.MuteRemoteAudioStream();
  133. //取消或恢复订阅指定远端用户的视频流。
  134. //RtcEngine.MuteRemoteVideoStream();
  135. }
  136. public void LeaveChannel()
  137. {
  138. int msg = RtcEngine.LeaveChannel();
  139. switch (msg)
  140. {
  141. case 0:
  142. LogText.text = "成功退出频道: "+_channelName;
  143. break;
  144. default:
  145. LogText.text = "退出频道失败: " + msg;
  146. break;
  147. }
  148. }
  149. private void StopPublish()
  150. {
  151. var options = new ChannelMediaOptions();
  152. options.publishMicrophoneTrack.SetValue(false);
  153. options.publishCameraTrack.SetValue(false);
  154. var nRet = RtcEngine.UpdateChannelMediaOptions(options);
  155. this.Log.UpdateLog("UpdateChannelMediaOptions: " + nRet);
  156. _stopPublishButton.gameObject.SetActive(false);
  157. _startPublishButton.gameObject.SetActive(true);
  158. }
  159. private void StartPublish()
  160. {
  161. var options = new ChannelMediaOptions();
  162. options.publishMicrophoneTrack.SetValue(true);
  163. options.publishCameraTrack.SetValue(true);
  164. var nRet = RtcEngine.UpdateChannelMediaOptions(options);
  165. this.Log.UpdateLog("UpdateChannelMediaOptions: " + nRet);
  166. _stopPublishButton.gameObject.SetActive(true);
  167. _startPublishButton.gameObject.SetActive(false);
  168. }
  169. private void OnDestroy()
  170. {
  171. Debug.Log("OnDestroy");
  172. if (RtcEngine == null) return;
  173. RtcEngine.InitEventHandler(null);
  174. RtcEngine.LeaveChannel();
  175. RtcEngine.Dispose();
  176. }
  177. internal string GetChannelName()
  178. {
  179. return _channelName;
  180. }
  181. internal static void MakeVideoView(uint uid, string channelId = "")
  182. {
  183. var go = GameObject.Find(uid.ToString());
  184. if (!ReferenceEquals(go, null))
  185. {
  186. return; // reuse
  187. }
  188. // create a GameObject and assign to this new user
  189. var videoSurface = MakeImageSurface(uid.ToString());
  190. if (ReferenceEquals(videoSurface, null)) return;
  191. // configure videoSurface
  192. if (uid == 0)
  193. {
  194. videoSurface.SetForUser(uid, channelId);
  195. }
  196. else
  197. {
  198. videoSurface.SetForUser(uid, channelId, VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  199. }
  200. videoSurface.OnTextureSizeModify += (int width, int height) =>
  201. {
  202. float scale = (float)height / (float)width;
  203. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  204. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  205. };
  206. videoSurface.SetEnable(true);
  207. }
  208. internal static void OnUserInfoUpdated(uint uid, Agora.Rtc.UserInfo info)
  209. {
  210. Debug.Log(info.uid);
  211. disUserPeer_Uid.Add("", info);
  212. }
  213. #region -- Video Render UI Logic ---
  214. // VIDEO TYPE 1: 3D Object
  215. private static VideoSurface MakePlaneSurface(string goName)
  216. {
  217. var go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  218. if (go == null)
  219. {
  220. return null;
  221. }
  222. go.name = goName;
  223. // set up transform
  224. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  225. var yPos = Random.Range(3.0f, 5.0f);
  226. var xPos = Random.Range(-2.0f, 2.0f);
  227. go.transform.position = Vector3.zero;
  228. go.transform.localScale = new Vector3(0.25f, 0.5f, 0.5f);
  229. // configure videoSurface
  230. var videoSurface = go.AddComponent<VideoSurface>();
  231. return videoSurface;
  232. }
  233. // Video TYPE 2: RawImage
  234. private static VideoSurface MakeImageSurface(string goName)
  235. {
  236. GameObject go = new GameObject();
  237. if (go == null)
  238. {
  239. return null;
  240. }
  241. go.name = goName;
  242. // to be renderered onto
  243. go.AddComponent<RawImage>();
  244. // make the object draggable
  245. go.AddComponent<UIElementDrag>();
  246. var canvas = GameObject.Find("VideoCanvas");
  247. if (canvas != null)
  248. {
  249. go.transform.parent = canvas.transform;
  250. Debug.Log("add video view");
  251. }
  252. else
  253. {
  254. Debug.Log("Canvas is null video view");
  255. }
  256. // set up transform
  257. go.transform.Rotate(0f, 0.0f, 180.0f);
  258. go.transform.localPosition = Vector3.zero;
  259. go.transform.localScale = new Vector3(2f, 3f, 1f);
  260. // configure videoSurface
  261. var videoSurface = go.AddComponent<VideoSurface>();
  262. return videoSurface;
  263. }
  264. internal static void DestroyVideoView(uint uid)
  265. {
  266. var go = GameObject.Find(uid.ToString());
  267. if (!ReferenceEquals(go, null))
  268. {
  269. Destroy(go);
  270. }
  271. }
  272. #endregion
  273. }
  274. #region -- Agora Event ---
  275. public class AgoraVideoTestEventHandler : IRtcEngineEventHandler
  276. {
  277. private readonly AgoraTestVideoNotToken _videoSample;
  278. internal AgoraVideoTestEventHandler(AgoraTestVideoNotToken videoSample)
  279. {
  280. _videoSample = videoSample;
  281. }
  282. public override void OnError(int err, string msg)
  283. {
  284. _videoSample.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  285. }
  286. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  287. {
  288. int build = 0;
  289. Debug.Log("Agora: OnJoinChannelSuccess ");
  290. _videoSample.Log.UpdateLog(string.Format("sdk version: ${0}",
  291. _videoSample.RtcEngine.GetVersion(ref build)));
  292. _videoSample.Log.UpdateLog(string.Format("sdk build: ${0}",
  293. build));
  294. _videoSample.Log.UpdateLog(
  295. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  296. connection.channelId, connection.localUid, elapsed));
  297. AgoraTestVideoNotToken.MakeVideoView(0);
  298. }
  299. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  300. {
  301. _videoSample.Log.UpdateLog("OnRejoinChannelSuccess");
  302. }
  303. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  304. {
  305. _videoSample.Log.UpdateLog("OnLeaveChannel");
  306. AgoraTestVideoNotToken.DestroyVideoView(0);
  307. }
  308. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole, CLIENT_ROLE_TYPE newRole)
  309. {
  310. _videoSample.Log.UpdateLog("OnClientRoleChanged");
  311. }
  312. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  313. {
  314. _videoSample.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  315. AgoraTestVideoNotToken.MakeVideoView(uid, _videoSample.GetChannelName());
  316. }
  317. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  318. {
  319. _videoSample.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  320. (int)reason));
  321. AgoraTestVideoNotToken.DestroyVideoView(uid);
  322. }
  323. public override void OnUserInfoUpdated(uint uid, Agora.Rtc.UserInfo info)
  324. {
  325. _videoSample.Log.UpdateLog(string.Format(" 用户 :${0} 加入房间", uid));
  326. AgoraTestVideoNotToken.OnUserInfoUpdated(uid, info);
  327. }
  328. public override void OnUplinkNetworkInfoUpdated(UplinkNetworkInfo info)
  329. {
  330. _videoSample.Log.UpdateLog("OnUplinkNetworkInfoUpdated");
  331. }
  332. public override void OnDownlinkNetworkInfoUpdated(DownlinkNetworkInfo info)
  333. {
  334. _videoSample.Log.UpdateLog("OnDownlinkNetworkInfoUpdated");
  335. }
  336. }
  337. #endregion