TRTCChatRoom.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. using ManageLiteAV;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.IO;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Vinno.FIS.TRTCClient.Common.Log;
  9. using Vinno.FIS.TRTCClient.Common.Pipe;
  10. using static Vinno.FIS.TRTCClient.TRTCPusher;
  11. namespace Vinno.FIS.TRTCClient
  12. {
  13. class TRTCChatRoom : ITRTCCloudCallback
  14. {
  15. private ITXDeviceManager _deviceManager;
  16. private ITRTCCloud _tRTCCloud;
  17. private string _localId;
  18. private uint _roomId;
  19. private bool _chatUserEnterRoomSuccess = false;
  20. private const int JoinAndLeaveRoomTimeout = 8000;
  21. private AutoResetEvent _joinRoomWiator = new AutoResetEvent(false);
  22. private AutoResetEvent _leafRoomWiator = new AutoResetEvent(false);
  23. private LocalVideoRenderCallback _localVideoRenderCallback;
  24. private RemoteVideoRenderCallback _remoteVideoRenderCallback;
  25. public event EventHandler<RemoteUserLeaveRoomArgs> RemoteUserLeaveRoomArrived;
  26. public event EventHandler TryToReconnect;
  27. private uint _connectTerminalRoomId;
  28. private uint _connectTerminalCameraRoomId;
  29. private int _reconnectTryCount;
  30. private string _connectTerminalId;
  31. private string _connectTerminalCameralId;
  32. /// <summary>
  33. /// Local camera video frame arrived
  34. /// </summary>
  35. public event EventHandler<VideoFrameArrivedArgs> LocalVideoFrameArrived;
  36. /// <summary>
  37. /// Remote device video frame arrived
  38. /// </summary>
  39. public event EventHandler<VideoFrameArrivedArgs> RemoteVideoFrameArrived;
  40. public event EventHandler OnTRTCEnterRoomError;
  41. public TRTCChatRoom(string logPath)
  42. {
  43. if (!Directory.Exists(logPath))
  44. {
  45. Directory.CreateDirectory(logPath);
  46. }
  47. _tRTCCloud = ITRTCCloud.getTRTCShareInstance();
  48. _tRTCCloud.setLogCompressEnabled(false);
  49. _tRTCCloud.setLogLevel(TRTCLogLevel.TRTCLogLevelError);
  50. _tRTCCloud.setLogDirPath(logPath);
  51. _localVideoRenderCallback = new LocalVideoRenderCallback(OnLocalVideoFrameArrived);
  52. _remoteVideoRenderCallback = new RemoteVideoRenderCallback(OnRemoteVideoFrameArrived);
  53. }
  54. public void Mute(bool isMute)
  55. {
  56. _tRTCCloud?.muteLocalAudio(isMute);
  57. }
  58. /// <summary>
  59. /// Enter chat room
  60. /// </summary>
  61. /// <param name="roomId"></param>
  62. /// <param name="accountId"></param>
  63. /// <param name="isChat">chat or terminal</param>
  64. /// <param name="onlyA
  65. /// udio">check audio or video chat</param>
  66. public void Enter(TRTCRoomInfo roomInfo)
  67. {
  68. Logger.WriteLineInfo($"RtcChatRoom {roomInfo.RoomId} Enter begin");
  69. if (_roomId <= 0)
  70. {
  71. _roomId = roomInfo.RoomId;
  72. _localId = roomInfo.UserId;
  73. Logger.WriteLineInfo($"_tRTCCloud version:{_tRTCCloud.getSDKVersion()}");
  74. _deviceManager = _tRTCCloud.getDeviceManager();
  75. var videoDeviceId = roomInfo.VideoDeviceId;
  76. if (!string.IsNullOrEmpty(roomInfo.VideoDeviceId))
  77. {
  78. videoDeviceId = GetCorrectDeviceId(roomInfo.VideoDeviceId, TRTCDeviceType.TXMediaDeviceTypeCamera);
  79. if (string.IsNullOrEmpty(videoDeviceId))
  80. {
  81. Logger.WriteLineError($"Can not get correct video device Id:{roomInfo.VideoDeviceId}");
  82. }
  83. }
  84. var micDeviceId = GetCorrectDeviceId(roomInfo.MicDeviceId, TRTCDeviceType.TXMediaDeviceTypeMic);
  85. if (string.IsNullOrEmpty(micDeviceId))
  86. {
  87. Logger.WriteLineError($"Can not get correct mic device Id:{roomInfo.MicDeviceId}");
  88. }
  89. var speakerDeviceId = GetCorrectDeviceId(roomInfo.SpeakerDeviceId, TRTCDeviceType.TXMediaDeviceTypeSpeaker);
  90. if (string.IsNullOrEmpty(speakerDeviceId))
  91. {
  92. Logger.WriteLineError($"Can not get correct video device Id:{roomInfo.SpeakerDeviceId}");
  93. }
  94. _deviceManager.setCurrentDevice(TRTCDeviceType.TXMediaDeviceTypeCamera, videoDeviceId);
  95. _deviceManager.setCurrentDevice(TRTCDeviceType.TXMediaDeviceTypeMic, micDeviceId);
  96. _deviceManager.setCurrentDevice(TRTCDeviceType.TXMediaDeviceTypeSpeaker, speakerDeviceId);
  97. var videoParam = GetVideoEncParam();
  98. _tRTCCloud.setVideoEncoderParam(ref videoParam);
  99. TRTCParams trtcParams = new TRTCParams();
  100. trtcParams.sdkAppId = (uint)roomInfo.AppId;
  101. trtcParams.roomId = (uint)roomInfo.RoomId;
  102. trtcParams.userId = roomInfo.UserId;
  103. trtcParams.userSig = roomInfo.UserSig;
  104. // 如果您有进房权限保护的需求,则参考文档{https://cloud.tencent.com/document/product/647/32240}完成该功能。
  105. // 在有权限进房的用户中的下面字段中添加在服务器获取到的privateMapKey。
  106. trtcParams.privateMapKey = "";
  107. trtcParams.businessInfo = "";
  108. //trtcParams.role =
  109. // 若您的项目有纯音频的旁路直播需求,请配置参数。
  110. // 配置该参数后,音频达到服务器,即开始自动旁路;
  111. // 否则无此参数,旁路在收到第一个视频帧之前,会将收到的音频包丢弃。
  112. //if (DataManager.GetInstance().pureAudioStyle)
  113. // trtcParams.businessInfo = "{\"Str_uc_params\":{\"pure_audio_push_mod\": 1}}";
  114. //else
  115. // trtcParams.businessInfo = "";
  116. _tRTCCloud.addCallback(this);
  117. _tRTCCloud.enterRoom(ref trtcParams, TRTCAppScene.TRTCAppSceneVideoCall);
  118. Logger.WriteLineInfo($"RtcChatRoom JoinRoom exectuted");
  119. if (!string.IsNullOrEmpty(roomInfo.VideoDeviceId))
  120. {
  121. _tRTCCloud.startLocalPreview(IntPtr.Zero);
  122. var retValue = _tRTCCloud.setLocalVideoRenderCallback(TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32,
  123. TRTCVideoBufferType.TRTCVideoBufferType_Buffer, _localVideoRenderCallback);
  124. //最新接口,TRTC已将原有本地视频渲染的老接口整合成TRTCRenderParams,
  125. //如不设置,本地画面预览会默认旋转90度
  126. var localVideoRenderParams = new TRTCRenderParams()
  127. {
  128. fillMode = TRTCVideoFillMode.TRTCVideoFillMode_Fit
  129. };
  130. _tRTCCloud.setLocalRenderParams(ref localVideoRenderParams);
  131. Logger.WriteLineInfo($"RtcChatRoom new room RegLocalVideo (1) - retValue{retValue}");
  132. }
  133. _tRTCCloud.startLocalAudio();
  134. Task.Run(() =>
  135. {
  136. if (!_joinRoomWiator.WaitOne(JoinAndLeaveRoomTimeout))
  137. {
  138. Logger.WriteLineWarn("RtcChatRoom Joint Room timeout");
  139. }
  140. });
  141. }
  142. else
  143. {
  144. if (!string.IsNullOrEmpty(roomInfo.VideoDeviceId))
  145. {
  146. _tRTCCloud.startLocalPreview(IntPtr.Zero);
  147. var retValue = _tRTCCloud.setLocalVideoRenderCallback(TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32,
  148. TRTCVideoBufferType.TRTCVideoBufferType_Buffer, _localVideoRenderCallback);
  149. Logger.WriteLineInfo($"RtcChatRoom old room RegLocalVideo (1)- retValue{retValue}");
  150. }
  151. _tRTCCloud.startLocalAudio();
  152. }
  153. Logger.WriteLineInfo($"RtcChatRoom {_roomId} Enter end");
  154. }
  155. /// <summary>
  156. /// Exit chat room
  157. /// </summary>
  158. public void Exit()
  159. {
  160. try
  161. {
  162. if (_tRTCCloud == null)
  163. {
  164. return;
  165. }
  166. Logger.WriteLineInfo($"RtcChatRoom {_roomId} Exit begin");
  167. _tRTCCloud.stopAllRemoteView();
  168. _tRTCCloud.stopLocalPreview();
  169. _tRTCCloud.stopLocalAudio();
  170. _tRTCCloud.muteLocalAudio(true);
  171. _tRTCCloud.muteLocalVideo(true);
  172. _roomId = 0;
  173. _localId = string.Empty;
  174. _connectTerminalRoomId = 0;
  175. _connectTerminalId = string.Empty;
  176. _connectTerminalCameralId = string.Empty;
  177. _tRTCCloud.exitRoom();
  178. if (_chatUserEnterRoomSuccess && !_leafRoomWiator.WaitOne(JoinAndLeaveRoomTimeout))
  179. {
  180. Logger.WriteLineWarn("RtcChatRoom exit Room timeout");
  181. }
  182. _chatUserEnterRoomSuccess = false;
  183. _tRTCCloud.removeCallback(this);
  184. _tRTCCloud.setLogCallback(null);
  185. _tRTCCloud = null;
  186. ITRTCCloud.destroyTRTCShareInstance();
  187. Logger.WriteLineInfo($"RtcChatRoom {_roomId} Exit and destroy tRTCCloud end ");
  188. }
  189. catch (Exception ex)
  190. {
  191. Logger.WriteLineError($"TRTCChatRoom Exit Error:{ex}");
  192. }
  193. }
  194. private TRTCVideoEncParam GetVideoEncParam()
  195. {
  196. TRTCVideoEncParam tRTCVideoEncParam = new TRTCVideoEncParam();
  197. tRTCVideoEncParam.videoResolution = TRTCVideoResolution.TRTCVideoResolution_640_480;
  198. tRTCVideoEncParam.videoFps = 15;
  199. tRTCVideoEncParam.videoBitrate = 1000;
  200. return tRTCVideoEncParam;
  201. }
  202. private static uint ParseRoomId(string roomId)
  203. {
  204. Guid value = new Guid(roomId);
  205. byte[] b = value.ToByteArray();
  206. //int bint = BitConverter.ToInt32(b, 0);
  207. //var bint1 = BitConverter.ToInt32(b, 4);
  208. //var bint2 = BitConverter.ToInt32(b, 8);
  209. var bint3 = Math.Abs(BitConverter.ToInt32(b, 12));
  210. Logger.WriteLineInfo($"ParseRoomId {roomId} to {bint3}");
  211. return (uint)bint3;
  212. }
  213. private void OnLocalVideoFrameArrived(TRTCVideoFrame data, string userId)
  214. {
  215. LocalVideoFrameArrived?.Invoke(this, new VideoFrameArrivedArgs(data, userId));
  216. }
  217. private void OnRemoteVideoFrameArrived(TRTCVideoFrame data, string userId)
  218. {
  219. RemoteVideoFrameArrived?.Invoke(this, new VideoFrameArrivedArgs(data, userId));
  220. }
  221. public void onError(TXLiteAVError errCode, string errMsg, IntPtr arg)
  222. {
  223. Logger.WriteLineError($"onError errCode:{errCode}, msg:{errMsg}, arg:{arg}");
  224. }
  225. public void onWarning(TXLiteAVWarning warningCode, string warningMsg, IntPtr arg)
  226. {
  227. Logger.WriteLineWarn($"onWarning errCode: {warningCode}, msg:{warningMsg}, arg:{arg}");
  228. }
  229. public void onEnterRoom(int result)
  230. {
  231. Logger.WriteLineInfo($"onEnterRoom result: {result}");
  232. _joinRoomWiator.Set();
  233. if (result >= 0)
  234. {
  235. _chatUserEnterRoomSuccess = true;
  236. }
  237. else
  238. {
  239. OnTRTCEnterRoomError?.Invoke(this, EventArgs.Empty);
  240. }
  241. }
  242. public void onExitRoom(int reason)
  243. {
  244. Logger.WriteLineInfo($"onExitRoom reason: {reason}");
  245. _leafRoomWiator.Set();
  246. }
  247. public void onSwitchRole(TXLiteAVError errCode, string errMsg)
  248. {
  249. Logger.WriteLineInfo($"onSwitchRole errCode: {errCode.ToString()}, errMsg: {errMsg}");
  250. }
  251. public void onConnectOtherRoom(string userId, TXLiteAVError errCode, string errMsg)
  252. {
  253. Logger.WriteLineInfo($"onConnectOtherRoom userId :{userId}, errCode: {errCode.ToString()}, errMsg: {errMsg}");
  254. if (errCode != TXLiteAVError.ERR_NULL && _reconnectTryCount <= 3)
  255. {
  256. ReconnectOtherRoom("onConnectOtherRoom failed", userId);
  257. }
  258. }
  259. public void onDisconnectOtherRoom(TXLiteAVError errCode, string errMsg)
  260. {
  261. Logger.WriteLineInfo($"onDisconnectOtherRoom errCode: {errCode}, errMsg: {errMsg}");
  262. }
  263. public void onRemoteUserEnterRoom(string userId)
  264. {
  265. //throw new NotImplementedException();
  266. }
  267. public void onRemoteUserLeaveRoom(string userId, int reason)
  268. {
  269. Logger.WriteLineInfo($"Remote User Leave Room,userId:{userId},reason:{reason}");
  270. RemoteUserLeaveRoomArrived?.Invoke(this, new RemoteUserLeaveRoomArgs(userId, reason));
  271. }
  272. public void onUserVideoAvailable(string userId, bool available)
  273. {
  274. if (available)
  275. {
  276. // 远端主流自定义渲染 View 动态绑定和监听 SDK 渲染回调
  277. _tRTCCloud.startRemoteView(userId, IntPtr.Zero);
  278. _tRTCCloud.setRemoteVideoRenderCallback(userId, TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32,
  279. TRTCVideoBufferType.TRTCVideoBufferType_Buffer, _remoteVideoRenderCallback);
  280. }
  281. else
  282. {
  283. // 远端主流自定义渲染 View 移除绑定
  284. _tRTCCloud.stopRemoteView(userId);
  285. _tRTCCloud.setRemoteVideoRenderCallback(userId, TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32,
  286. TRTCVideoBufferType.TRTCVideoBufferType_Buffer, null);
  287. if (!string.IsNullOrEmpty(_connectTerminalId) && _connectTerminalId == userId && _reconnectTryCount <= 3)
  288. {
  289. Task.Run(() =>
  290. {
  291. ReconnectOtherRoom("onUserVideoAvailable false", userId);
  292. });
  293. }
  294. else if (!string.IsNullOrEmpty(_connectTerminalCameralId) && _connectTerminalCameralId == userId && _reconnectTryCount <= 3)
  295. {
  296. Task.Run(() =>
  297. {
  298. ReconnectOtherRoom("onUserVideoAvailable false", userId);
  299. });
  300. }
  301. }
  302. Logger.WriteLineInfo($"onUserVideoAvailable userId: {userId}, available: {available}");
  303. }
  304. private async void ReconnectOtherRoom(string reason, string userId)
  305. {
  306. await Task.Delay(1000);
  307. if (_chatUserEnterRoomSuccess)
  308. {
  309. if (userId == _connectTerminalId)
  310. {
  311. Logger.WriteLineInfo($"Reason:{reason}, OnReconnect Other Room userId: {_connectTerminalId}, roomId {_connectTerminalRoomId}");
  312. ConnectTerminalRoom(_connectTerminalRoomId, _connectTerminalId);
  313. _reconnectTryCount++;
  314. }
  315. else if (userId == _connectTerminalCameralId)
  316. {
  317. Logger.WriteLineInfo($"Reason:{reason}, OnReconnect Other Room userId: {_connectTerminalCameralId}, roomId {_connectTerminalCameraRoomId}");
  318. ConnectTerminalCameraRoom(_connectTerminalCameraRoomId, _connectTerminalCameralId);
  319. _reconnectTryCount++;
  320. }
  321. }
  322. }
  323. public void onUserSubStreamAvailable(string userId, bool available)
  324. {
  325. //throw new NotImplementedException();
  326. }
  327. public void onUserAudioAvailable(string userId, bool available)
  328. {
  329. Logger.WriteLineInfo($"onUserAudioAvailable userId: {userId}, available: {available}");
  330. }
  331. public void onFirstVideoFrame(string userId, TRTCVideoStreamType streamType, int width, int height)
  332. {
  333. Logger.WriteLineInfo($"onFirstVideoFrame userId: {userId}, streamType: {streamType.ToString()}, width:{width}, height:{height}");
  334. }
  335. public void onFirstAudioFrame(string userId)
  336. {
  337. Logger.WriteLineInfo($"onFirstAudioFrame userId: {userId}");
  338. }
  339. public void onSendFirstLocalVideoFrame(TRTCVideoStreamType streamType)
  340. {
  341. //throw new NotImplementedException();
  342. }
  343. public void onSendFirstLocalAudioFrame()
  344. {
  345. //throw new NotImplementedException();
  346. }
  347. public void onUserEnter(string userId)
  348. {
  349. //throw new NotImplementedException();
  350. }
  351. public void onUserExit(string userId, int reason)
  352. {
  353. //throw new NotImplementedException();
  354. }
  355. public void onNetworkQuality(TRTCQualityInfo localQuality, TRTCQualityInfo[] remoteQuality, uint remoteQualityCount)
  356. {
  357. //throw new NotImplementedException();
  358. }
  359. public void onStatistics(TRTCStatistics statis)
  360. {
  361. //throw new NotImplementedException();
  362. }
  363. public void onConnectionLost()
  364. {
  365. Logger.WriteLineInfo($"onConnectionLost");
  366. }
  367. public void onTryToReconnect()
  368. {
  369. Logger.WriteLineInfo($"onTryToReconnect");
  370. TryToReconnect?.Invoke(this, EventArgs.Empty);
  371. }
  372. public void onConnectionRecovery()
  373. {
  374. Logger.WriteLineInfo($"onConnectionRecovery");
  375. }
  376. public void onSpeedTest(TRTCSpeedTestResult currentResult, uint finishedCount, uint totalCount)
  377. {
  378. //throw new NotImplementedException();
  379. }
  380. public void onCameraDidReady()
  381. {
  382. Logger.WriteLineInfo($"onCameraDidReady");
  383. }
  384. public void onMicDidReady()
  385. {
  386. Logger.WriteLineInfo($"onMicDidReady");
  387. }
  388. public void onUserVoiceVolume(TRTCVolumeInfo[] userVolumes, uint userVolumesCount, uint totalVolume)
  389. {
  390. //throw new NotImplementedException();
  391. }
  392. public void onDeviceChange(string deviceId, TRTCDeviceType type, TRTCDeviceState state)
  393. {
  394. //throw new NotImplementedException();
  395. }
  396. public void onTestMicVolume(uint volume)
  397. {
  398. //throw new NotImplementedException();
  399. }
  400. public void onTestSpeakerVolume(uint volume)
  401. {
  402. //throw new NotImplementedException();
  403. }
  404. public void onRecvCustomCmdMsg(string userId, int cmdID, uint seq, byte[] msg, uint msgSize)
  405. {
  406. //throw new NotImplementedException();
  407. }
  408. public void onMissCustomCmdMsg(string userId, int cmdId, int errCode, int missed)
  409. {
  410. //throw new NotImplementedException();
  411. }
  412. public void onRecvSEIMsg(string userId, byte[] message, uint msgSize)
  413. {
  414. //throw new NotImplementedException();
  415. }
  416. public void onStartPublishCDNStream(int errCode, string errMsg)
  417. {
  418. //throw new NotImplementedException();
  419. }
  420. public void onStopPublishCDNStream(int errCode, string errMsg)
  421. {
  422. //throw new NotImplementedException();
  423. }
  424. public void onSetMixTranscodingConfig(int errCode, string errMsg)
  425. {
  426. //throw new NotImplementedException();
  427. }
  428. public void onAudioEffectFinished(int effectId, int code)
  429. {
  430. //throw new NotImplementedException();
  431. }
  432. public void onScreenCaptureCovered()
  433. {
  434. //throw new NotImplementedException();
  435. }
  436. public void onScreenCaptureStarted()
  437. {
  438. //throw new NotImplementedException();
  439. }
  440. public void onScreenCapturePaused(int reason)
  441. {
  442. //throw new NotImplementedException();
  443. }
  444. public void onScreenCaptureResumed(int reason)
  445. {
  446. //throw new NotImplementedException();
  447. }
  448. public void onScreenCaptureStoped(int reason)
  449. {
  450. //throw new NotImplementedException();
  451. }
  452. public void onPlayBGMBegin(TXLiteAVError errCode)
  453. {
  454. //throw new NotImplementedException();
  455. }
  456. public void onPlayBGMProgress(uint progressMS, uint durationMS)
  457. {
  458. //throw new NotImplementedException();
  459. }
  460. public void onPlayBGMComplete(TXLiteAVError errCode)
  461. {
  462. //throw new NotImplementedException();
  463. }
  464. /// <summary>
  465. /// Connect tarminal room
  466. /// </summary>
  467. /// <param name="roomId"></param>
  468. /// <param name="terminalId"></param>
  469. internal void ConnectTerminalRoom(uint roomId, string terminalId)
  470. {
  471. //_tRTCCloud.connectOtherRoom("{\"roomId\":\"1767270833\",\"userId\":\"" + accountId + "\"}");
  472. // Thread.Sleep(200);
  473. dynamic jsonObj = new JObject();
  474. jsonObj["roomId"] = roomId;
  475. jsonObj["userId"] = terminalId;
  476. _connectTerminalRoomId = roomId;
  477. _reconnectTryCount = 0;
  478. _connectTerminalId = terminalId;
  479. var jsonData = JsonConvert.SerializeObject(jsonObj);
  480. Logger.WriteLineInfo($"TRTC ConnectRoom Room id {roomId} -Terminal id: {terminalId}");
  481. _tRTCCloud.connectOtherRoom(jsonData);
  482. }
  483. /// <summary>
  484. /// Connect tarminal room
  485. /// </summary>
  486. /// <param name="roomId"></param>
  487. /// <param name="terminalId"></param>
  488. internal void ConnectTerminalCameraRoom(uint roomId, string cameraId)
  489. {
  490. //_tRTCCloud.connectOtherRoom("{\"roomId\":\"1767270833\",\"userId\":\"" + accountId + "\"}");
  491. // Thread.Sleep(200);
  492. dynamic jsonObj = new JObject();
  493. jsonObj["roomId"] = roomId;
  494. jsonObj["userId"] = cameraId;
  495. _connectTerminalCameralId = cameraId;
  496. _connectTerminalCameraRoomId = roomId;
  497. var jsonData = JsonConvert.SerializeObject(jsonObj);
  498. Logger.WriteLineInfo($"TRTC ConnectRoom Room id {roomId} -Terminal Camera id: {cameraId}");
  499. _tRTCCloud.connectOtherRoom(jsonData);
  500. }
  501. public void onStartPublishing(int errCode, string errMsg)
  502. {
  503. Logger.WriteLineInfo($"onStartPublishing errCode: {errCode}, errMsg: {errMsg}");
  504. }
  505. public void onStopPublishing(int errCode, string errMsg)
  506. {
  507. Logger.WriteLineInfo($"onStopPublishing errCode: {errCode}, errMsg: {errMsg}");
  508. }
  509. public void onSwitchRoom(TXLiteAVError errCode, string errMsg)
  510. {
  511. Logger.WriteLineInfo($"onSwitchRoom: {errCode}, errMsg: {errMsg}");
  512. }
  513. public void onAudioDeviceCaptureVolumeChanged(uint volume, bool muted)
  514. {
  515. Logger.WriteLineInfo($"onAudioDeviceCaptureVolumeChanged: {volume}, errMsg: {muted}");
  516. }
  517. public void onAudioDevicePlayoutVolumeChanged(uint volume, bool muted)
  518. {
  519. Logger.WriteLineInfo($"onAudioDevicePlayoutVolumeChanged: {volume}, errMsg: {muted}");
  520. }
  521. private string GetCorrectDeviceId(string deviceId, TRTCDeviceType deviceType)
  522. {
  523. if (string.IsNullOrEmpty(deviceId))
  524. {
  525. return string.Empty;
  526. }
  527. var deviceList = _deviceManager.getDevicesList(deviceType);
  528. try
  529. {
  530. var count = deviceList.getCount();
  531. for (uint i = 0; i < count; i++)
  532. {
  533. var id = deviceList.getDevicePID(i);
  534. if (deviceId.Contains(id) || id.Contains(deviceId))
  535. {
  536. return id;
  537. }
  538. }
  539. }
  540. finally
  541. {
  542. deviceList.release();
  543. }
  544. return string.Empty;
  545. }
  546. internal void SwitchMic(string micId)
  547. {
  548. if (_tRTCCloud != null)
  549. {
  550. _tRTCCloud.stopLocalAudio();
  551. var correctMicId = GetCorrectId(HardwareType.Mic, micId);
  552. if (!string.IsNullOrEmpty(correctMicId))
  553. {
  554. var deviceManager = _tRTCCloud.getDeviceManager();
  555. deviceManager.setCurrentDevice(TRTCDeviceType.TXMediaDeviceTypeMic, correctMicId);
  556. _tRTCCloud.startLocalAudio();//开启本地音频的采集和上行
  557. }
  558. }
  559. }
  560. /// <summary>
  561. /// Get the Correct Id
  562. /// </summary>
  563. /// <param name="type"></param>
  564. /// <param name="deviceId"></param>
  565. /// <returns></returns>
  566. private string GetCorrectId(HardwareType type, string deviceId)
  567. {
  568. switch (type)
  569. {
  570. case HardwareType.Camera:
  571. var cameraList = _deviceManager.getDevicesList(TRTCDeviceType.TXMediaDeviceTypeCamera);
  572. try
  573. {
  574. var count = cameraList.getCount();
  575. for (uint i = 0; i < count; i++)
  576. {
  577. var id = cameraList.getDevicePID(i);
  578. if (deviceId.Contains(id) || id.Contains(deviceId))
  579. {
  580. return id;
  581. }
  582. }
  583. }
  584. finally
  585. {
  586. cameraList.release();
  587. }
  588. break;
  589. case HardwareType.Mic:
  590. var micList = _deviceManager.getDevicesList(TRTCDeviceType.TXMediaDeviceTypeMic);
  591. try
  592. {
  593. var count = micList.getCount();
  594. for (uint i = 0; i < count; i++)
  595. {
  596. var id = micList.getDevicePID(i);
  597. if (deviceId.Contains(id) || id.Contains(deviceId))
  598. {
  599. return id;
  600. }
  601. }
  602. }
  603. finally
  604. {
  605. micList.release();
  606. }
  607. break;
  608. case HardwareType.Speaker:
  609. var speakerList = _deviceManager.getDevicesList(TRTCDeviceType.TXMediaDeviceTypeSpeaker);
  610. try
  611. {
  612. var count = speakerList.getCount();
  613. for (uint i = 0; i < count; i++)
  614. {
  615. var id = speakerList.getDevicePID(i);
  616. if (deviceId.Contains(id) || id.Contains(deviceId))
  617. {
  618. return id;
  619. }
  620. }
  621. }
  622. finally
  623. {
  624. speakerList.release();
  625. }
  626. break;
  627. }
  628. return string.Empty;
  629. }
  630. }
  631. }