StreamMessage.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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;
  8. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.StreamMessage
  9. {
  10. public class StreamMessage : MonoBehaviour
  11. {
  12. [FormerlySerializedAs("appIdInput")]
  13. [SerializeField]
  14. private AppIdInput _appIdInput;
  15. [Header("_____________Basic Configuration_____________")]
  16. [FormerlySerializedAs("APP_ID")]
  17. [SerializeField]
  18. public string _appID = "";
  19. [FormerlySerializedAs("TOKEN")]
  20. [SerializeField]
  21. public string _token = "";
  22. [FormerlySerializedAs("CHANNEL_NAME")]
  23. [SerializeField]
  24. public string _channelName = "";
  25. public Text LogText;
  26. internal Logger Log;
  27. internal IRtcEngine RtcEngine;
  28. private int _streamId = -1;
  29. private void Start()
  30. {
  31. LoadAssetData();
  32. if (CheckAppId())
  33. {
  34. InitEngine();
  35. SetupUI();
  36. EnableUI(false);
  37. JoinChannel();
  38. }
  39. }
  40. [ContextMenu("ShowAgoraBasicProfileData")]
  41. private void LoadAssetData()
  42. {
  43. if (_appIdInput == null) return;
  44. _appID = _appIdInput.appID;
  45. _token = _appIdInput.token;
  46. _channelName = _appIdInput.channelName;
  47. }
  48. private bool CheckAppId()
  49. {
  50. Log = new Logger(LogText);
  51. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  52. }
  53. private void InitEngine()
  54. {
  55. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  56. UserEventHandler handler = new UserEventHandler(this);
  57. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  58. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  59. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
  60. RtcEngine.Initialize(context);
  61. RtcEngine.InitEventHandler(handler);
  62. }
  63. private void JoinChannel()
  64. {
  65. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  66. RtcEngine.EnableAudio();
  67. RtcEngine.JoinChannel(_token, _channelName, "");
  68. }
  69. private void Update()
  70. {
  71. PermissionHelper.RequestMicrophontPermission();
  72. }
  73. private void SetupUI()
  74. {
  75. var ui = this.transform.Find("UI");
  76. var btn = ui.Find("SendButton").GetComponent<Button>();
  77. btn.onClick.AddListener(onSendButtonPress);
  78. }
  79. public void EnableUI(bool visible)
  80. {
  81. var ui = this.transform.Find("UI");
  82. ui.gameObject.SetActive(visible);
  83. }
  84. private void onSendButtonPress()
  85. {
  86. var text = this.transform.Find("UI/InputField").GetComponent<InputField>();
  87. if (text.text == "")
  88. {
  89. Log.UpdateLog("Dont send empty message!");
  90. }
  91. int streamId = this.CreateDataStreamId();
  92. if (streamId < 0)
  93. {
  94. Log.UpdateLog("CreateDataStream failed!");
  95. return;
  96. }
  97. else
  98. {
  99. SendStreamMessage(streamId, text.text);
  100. text.text = "";
  101. }
  102. }
  103. private int CreateDataStreamId()
  104. {
  105. if (this._streamId == -1)
  106. {
  107. var config = new DataStreamConfig();
  108. config.syncWithAudio = false;
  109. config.ordered = true;
  110. var nRet = RtcEngine.CreateDataStream(ref this._streamId, config);
  111. this.Log.UpdateLog(string.Format("CreateDataStream: nRet{0}, streamId{1}", nRet, _streamId));
  112. }
  113. return _streamId;
  114. }
  115. private void SendStreamMessage(int streamId, string message)
  116. {
  117. byte[] byteArray = System.Text.Encoding.Default.GetBytes(message);
  118. var nRet = RtcEngine.SendStreamMessage(streamId, byteArray, Convert.ToUInt32(byteArray.Length));
  119. this.Log.UpdateLog("SendStreamMessage :" + nRet);
  120. }
  121. private void OnDestroy()
  122. {
  123. Debug.Log("OnDestroy");
  124. if (RtcEngine == null) return;
  125. RtcEngine.InitEventHandler(null);
  126. RtcEngine.LeaveChannel();
  127. RtcEngine.Dispose();
  128. }
  129. }
  130. #region -- Agora Event ---
  131. internal class UserEventHandler : IRtcEngineEventHandler
  132. {
  133. private readonly StreamMessage _streamMessage;
  134. internal UserEventHandler(StreamMessage videoSample)
  135. {
  136. _streamMessage = videoSample;
  137. }
  138. public override void OnError(int err, string msg)
  139. {
  140. _streamMessage.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  141. }
  142. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  143. {
  144. int build = 0;
  145. Debug.Log("Agora: OnJoinChannelSuccess ");
  146. _streamMessage.Log.UpdateLog(string.Format("sdk version: ${0}",
  147. _streamMessage.RtcEngine.GetVersion(ref build)));
  148. _streamMessage.Log.UpdateLog(
  149. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  150. connection.channelId, connection.localUid, elapsed));
  151. _streamMessage.EnableUI(true);
  152. }
  153. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  154. {
  155. _streamMessage.Log.UpdateLog("OnRejoinChannelSuccess");
  156. }
  157. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  158. {
  159. _streamMessage.Log.UpdateLog("OnLeaveChannel");
  160. _streamMessage.EnableUI(false);
  161. }
  162. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole, CLIENT_ROLE_TYPE newRole)
  163. {
  164. _streamMessage.Log.UpdateLog("OnClientRoleChanged");
  165. }
  166. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  167. {
  168. _streamMessage.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  169. }
  170. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  171. {
  172. _streamMessage.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  173. (int)reason));
  174. }
  175. public override void OnStreamMessage(RtcConnection connection, uint remoteUid, int streamId, byte[] data, uint length, ulong sentTs)
  176. {
  177. string streamMessage = System.Text.Encoding.Default.GetString(data);
  178. _streamMessage.Log.UpdateLog(string.Format("OnStreamMessage remoteUid: {0}, stream message: {1}", remoteUid, streamMessage));
  179. }
  180. public override void OnStreamMessageError(RtcConnection connection, uint remoteUid, int streamId, int code, int missed, int cached)
  181. {
  182. _streamMessage.Log.UpdateLog(string.Format("OnStreamMessageError remoteUid: {0}, streamId: {1}, code: {2}, missed: {3}, cached: {4}", remoteUid, streamId, code, missed, cached));
  183. }
  184. }
  185. #endregion
  186. }