TRTCChatRoom.cs 26 KB

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