XYChatRoomRTCManager.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. //
  2. // XYChatRoomRTCManager.m
  3. // Starbuds
  4. //
  5. // Created by 翟玉磊 on 2020/7/9.
  6. // Copyright © 2020 翟玉磊. All rights reserved.
  7. //
  8. #import "XYChatRoomRTCManager.h"
  9. #import <ZegoExpressEngine/ZegoExpressEngine.h>
  10. typedef void(^ChatRoomRTCBlock)(NSInteger errCode, NSString *errMsg);
  11. @interface XYChatRoomRTCManager ()<ZegoEventHandler, ZegoMediaPlayerEventHandler>
  12. @property (nonatomic, copy) ChatRoomRTCBlock chatRoomRTCBlock;
  13. @property (nonatomic, copy) NSString *userId;
  14. @property (nonatomic, copy) NSString *streamId;
  15. @property (nonatomic, copy) NSString *currentPlayMusicId;
  16. @property (nonatomic, strong) ZegoMediaPlayer *mediaPlayer;
  17. /// 是否启用麦克风(音频采集)YES打开输出设备 NO关闭输出设备
  18. @property (nonatomic, assign) BOOL enableMicrophone;
  19. /// 跨房pk的流id数组
  20. @property (nonatomic, strong) NSMutableArray *kfPkStreamIds;
  21. @end
  22. @implementation XYChatRoomRTCManager
  23. - (void)clear {
  24. // 关闭播放器
  25. if (_mediaPlayer) {
  26. [_mediaPlayer stop];
  27. _mediaPlayer = nil;
  28. }
  29. // 销毁引擎
  30. [ZegoExpressEngine destroyEngine:nil];
  31. }
  32. - (instancetype)init {
  33. if (self = [super init]) {
  34. [self initValue];
  35. [self initRtcEngineKit];
  36. }
  37. return self;
  38. }
  39. - (void)initValue {
  40. self.kfPkMute = NO;
  41. self.kfPkStreamIds = [NSMutableArray array];
  42. self.enableMicrophone = NO;
  43. }
  44. - (void)initRtcEngineKit {
  45. NSLog(@"即构SDK版本:%@", [ZegoExpressEngine getVersion]);
  46. unsigned int appId = [[XYChannelInfoManager sharedInstance].JGAppId unsignedIntValue];
  47. NSString *appSign = [XYChannelInfoManager sharedInstance].JGAppSign;
  48. BOOL isTestEnv = NO;
  49. if ([ZYLService currentService].environment == ZYLServiceEnvironmentTest || [ZYLService currentService].environment == ZYLServiceEnvironmentDevelop || [ZYLService currentService].environment == ZYLServiceEnvironmentTestGy) {
  50. isTestEnv = YES;
  51. }
  52. // 设置房间模式为多房间模式
  53. // [ZegoExpressEngine setRoomMode:ZegoRoomModeMultiRoom];
  54. // 启动引擎
  55. // [ZegoExpressEngine createEngineWithAppID:appId appSign:appSign isTestEnv:isTestEnv scenario:ZegoScenarioGeneral eventHandler:self];
  56. ZegoEngineProfile *profile = [[ZegoEngineProfile alloc] init];
  57. profile.appID = appId;
  58. profile.appSign = appSign;
  59. //通用场景接入,请根据实际情况选择合适的场景
  60. profile.scenario = ZegoScenarioDefault;
  61. // 创建引擎,并注册 self 为 eventHandler 回调。不需要注册回调的话,eventHandler 参数可以传 nil,后续可调用 "-setEventHandler:" 方法设置回调
  62. [ZegoExpressEngine createEngineWithProfile:profile eventHandler:self];
  63. // 切换音频设备默认
  64. NSString *params = @"{\"method\":\"express.video.set_audio_device_mode\",\"params\":{\"mode\":6}}";
  65. [[ZegoExpressEngine sharedEngine] callExperimentalAPI:params];
  66. // 音频配置
  67. ZegoAudioConfig *audioConfig = [ZegoAudioConfig defaultConfig];
  68. audioConfig.codecID = ZegoAudioCodecIDLow3;
  69. [[ZegoExpressEngine sharedEngine] setAudioConfig:audioConfig];
  70. // 预览
  71. [[ZegoExpressEngine sharedEngine] startPreview];
  72. [[ZegoExpressEngine sharedEngine] stopPreview];
  73. // 先退出所有房间 防止异常关闭
  74. [[ZegoExpressEngine sharedEngine] logoutRoom];
  75. }
  76. - (void)setKfPKRoomId:(NSString *)kfPKRoomId {
  77. _kfPKRoomId = kfPKRoomId;
  78. if (StringIsEmpty(kfPKRoomId)) {
  79. // 停止拉流
  80. for (NSString *streamId in self.kfPkStreamIds) {
  81. [[ZegoExpressEngine sharedEngine] stopPlayingStream:streamId];
  82. }
  83. }
  84. [self.kfPkStreamIds removeAllObjects];
  85. }
  86. - (void)setKfPkMute:(BOOL)kfPkMute {
  87. _kfPkMute = kfPkMute;
  88. // 更新流静音状态
  89. for (NSString *streamId in self.kfPkStreamIds) {
  90. [[ZegoExpressEngine sharedEngine] mutePlayStreamAudio:kfPkMute streamID:streamId];
  91. }
  92. }
  93. /// 加入房间
  94. /// @param roomId 房间id
  95. /// @param userId 用户id
  96. - (void)joinRoomWithRoomId:(NSString *)roomId userId:(NSString *)userId token:(NSString *)token resultBlock:(void(^)(NSInteger errCode, NSString *errMsg))block {
  97. if (StringIsEmpty(roomId)) {
  98. return;
  99. }
  100. self.userId = [userId copy];
  101. if (block) {
  102. self.chatRoomRTCBlock = block;
  103. }
  104. // 创建用户对象
  105. ZegoUser *user = [ZegoUser userWithUserID:self.userId];
  106. // 房间配置
  107. ZegoRoomConfig *config = [ZegoRoomConfig defaultConfig];
  108. config.isUserStatusNotify = YES;
  109. if (StringIsNotEmpty(token)) {
  110. config.token = token;
  111. }
  112. // 开始登录房间
  113. [[ZegoExpressEngine sharedEngine] loginRoom:roomId user:user];
  114. // 启动声浪监控
  115. [[ZegoExpressEngine sharedEngine] startSoundLevelMonitor];
  116. }
  117. /// 退出房间
  118. /// @param roomId 房间id
  119. /// @param block 回调
  120. - (void)exitRoomWithRoomId:(NSString *)roomId resultBlock:(void(^)(NSInteger errCode, NSString *errMsg))block {
  121. if (block) {
  122. self.chatRoomRTCBlock = block;
  123. }
  124. // 停止声浪监控
  125. [[ZegoExpressEngine sharedEngine] stopSoundLevelMonitor];
  126. // 开始登出房间
  127. [[ZegoExpressEngine sharedEngine] logoutRoom:roomId];
  128. }
  129. /// 开始推流
  130. - (void)startPublishingStream:(NSString *)streamId roomId:(NSString *)roomId resultBlock:(void(^ _Nullable)(NSInteger errCode, NSString *errMsg))block {
  131. if (streamId.length == 0) {
  132. return;
  133. }
  134. self.streamId = streamId;
  135. self.chatRoomRTCBlock = block;
  136. // 开始推流
  137. ZegoPublisherConfig *config = [[ZegoPublisherConfig alloc] init];
  138. config.roomID = [roomId copy];
  139. [[ZegoExpressEngine sharedEngine] startPublishingStream:streamId config:config channel:ZegoPublishChannelMain];
  140. }
  141. /// 停止推流
  142. - (void)stopPublishingStreamResultBlock:(void(^ _Nullable)(NSInteger errCode, NSString *errMsg))block {
  143. self.chatRoomRTCBlock = block;
  144. // 停止推流
  145. [[ZegoExpressEngine sharedEngine] stopPublishingStream];
  146. }
  147. /// 检查音频输入是否静音
  148. - (BOOL)isSpeakerMuted {
  149. return [[ZegoExpressEngine sharedEngine] isSpeakerMuted];
  150. }
  151. /// 是否静音(关闭音频输入) YES:表示静音音频输入关闭 NO:表示音频输入没有关闭
  152. - (void)muteSpeaker:(BOOL)mute {
  153. [[ZegoExpressEngine sharedEngine] muteSpeaker:mute];
  154. }
  155. /// 检查麦克风是否关闭 YES关闭 NO开启
  156. - (BOOL)isMicrophoneMuted {
  157. return [[ZegoExpressEngine sharedEngine] isMicrophoneMuted];
  158. }
  159. /// 是否关闭麦克风 YES关闭 NO开启
  160. - (void)muteMicrophone:(BOOL)mute {
  161. self.enableMicrophone = !mute;
  162. [[ZegoExpressEngine sharedEngine] muteMicrophone:mute];
  163. if (_mediaPlayer) {
  164. // 禁止背景音乐输出
  165. [_mediaPlayer enableAux:!mute];
  166. }
  167. }
  168. /// 开/关音频采集设备 YES 表示打开音频采集设备;NO 表示关闭音频采集设备
  169. - (void)enableAudioCaptureDevice:(BOOL)enable {
  170. [[ZegoExpressEngine sharedEngine] enableAudioCaptureDevice:enable];
  171. self.enableMicrophone = enable;
  172. }
  173. /// 设置音频路由到扬声器
  174. /// @param defaultToSpeaker 是否使用内置扬声器播放声音,YES 表示使用内置扬声器播放声音,NO 表示使用当前系统调度的优先级最高的音频输出设备播放声音
  175. - (void)setAudioRouteToSpeaker:(BOOL)defaultToSpeaker {
  176. [[ZegoExpressEngine sharedEngine] setAudioRouteToSpeaker:defaultToSpeaker];
  177. }
  178. #pragma mark - ZegoEventHandler
  179. // 调试错误信息回调
  180. - (void)onDebugError:(int)errorCode funcName:(NSString *)funcName info:(NSString *)info {
  181. NSLog(@"即构SDK报错信息:errorCode:%d, info:%@", errorCode, info);
  182. NSString *errMsg = info;
  183. switch (errorCode) {
  184. case 1000002:
  185. errMsg = @"未登录房间";
  186. break;
  187. case 1002064:
  188. errMsg = @"房间ID已被登录房间接口使用,未退出房间之前,当前用户无法再登录该房间";
  189. break;
  190. default:
  191. break;
  192. }
  193. !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(errorCode, errMsg);
  194. }
  195. // 音视频引擎状态更新的回调通知
  196. - (void)onEngineStateUpdate:(ZegoEngineState)state {
  197. if (state == ZegoEngineStateStart) {
  198. NSLog(@"即构SDK引擎正常");
  199. }else {
  200. NSLog(@"即构SDK引擎停止");
  201. }
  202. }
  203. // 房间状态变化通知
  204. - (void)onRoomStateChanged:(ZegoRoomStateChangedReason)reason errorCode:(int)errorCode extendedData:(NSDictionary *)extendedData roomID:(NSString *)roomID{
  205. NSLog(@"既构onRoomStateChanged=%d %d %@ %@,",reason,errorCode,extendedData,roomID);
  206. [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"既构onRoomStateChanged=%d %d %@ %@,",reason,errorCode,extendedData,roomID]];
  207. if (reason == ZegoRoomStateChangedReasonLogined && errorCode == 0) {
  208. NSLog(@"登录房间成功");
  209. !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(0, @"");
  210. }
  211. if (reason == ZegoRoomStateChangedReasonKickOut && errorCode == 0) {
  212. NSLog(@"退出房间成功");
  213. !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(0, @"");
  214. }
  215. if (errorCode != 0) {
  216. NSLog(@"房间状态变更失败");
  217. NSString *errMsg = @"请求失败";
  218. if (errorCode == 1002036) {
  219. // 没有开通多房间模式
  220. errMsg = @"没有开通多房间模式";
  221. }
  222. !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(errorCode, [NSString stringWithFormat:@"%@ %d", errMsg, errorCode]);
  223. }
  224. }
  225. //- (void)onRoomStateUpdate:(ZegoRoomState)state errorCode:(int)errorCode extendedData:(NSDictionary *)extendedData roomID:(NSString *)roomID {
  226. // NSLog(@"既构onRoomStateUpdate=%d %d %@ %@,",state,errorCode,extendedData,roomID);
  227. // [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"既构onRoomStateUpdate=%d %d %@ %@,",state,errorCode,extendedData,roomID]];
  228. // if (state == ZegoRoomStateConnected && errorCode == 0) {
  229. // NSLog(@"登录房间成功");
  230. // !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(0, @"");
  231. // }
  232. // if (state == ZegoRoomStateDisconnected && errorCode == 0) {
  233. // NSLog(@"退出房间成功");
  234. // !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(0, @"");
  235. // }
  236. // if (errorCode != 0) {
  237. // NSLog(@"房间状态变更失败");
  238. // NSString *errMsg = @"请求失败";
  239. // if (errorCode == 1002036) {
  240. // // 没有开通多房间模式
  241. // errMsg = @"没有开通多房间模式";
  242. // }
  243. // !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(errorCode, [NSString stringWithFormat:@"%@ %d", errMsg, errorCode]);
  244. // }
  245. //}
  246. // 房间内其他用户增加或减少的回调通知
  247. - (void)onRoomUserUpdate:(ZegoUpdateType)updateType userList:(NSArray<ZegoUser *> *)userList roomID:(NSString *)roomID {
  248. if (updateType == ZegoUpdateTypeAdd) {
  249. }
  250. if (updateType == ZegoUpdateTypeDelete) {
  251. }
  252. }
  253. // 房间内当前在线用户数量回调
  254. - (void)onRoomOnlineUserCountUpdate:(int)count roomID:(NSString *)roomID {
  255. }
  256. // 相同房间内其他用户推的流增加或减少的通知
  257. - (void)onRoomStreamUpdate:(ZegoUpdateType)updateType streamList:(NSArray<ZegoStream *> *)streamList extendedData:(NSDictionary *)extendedData roomID:(NSString *)roomID {
  258. for (ZegoStream *stream in streamList) {
  259. if (updateType == ZegoUpdateTypeAdd) {
  260. // 开始拉流
  261. ZegoPlayerConfig *config = [[ZegoPlayerConfig alloc] init];
  262. config.roomID = roomID;
  263. [[ZegoExpressEngine sharedEngine] startPlayingStream:stream.streamID config:config];
  264. // 跨发PK静音控制
  265. if ([roomID isEqualToString:self.kfPKRoomId]) {
  266. [self.kfPkStreamIds addObject:stream.streamID];
  267. if (self.kfPkMute) {
  268. [[ZegoExpressEngine sharedEngine] mutePlayStreamAudio:self.kfPkMute streamID:stream.streamID];
  269. }
  270. }
  271. }
  272. if (updateType == ZegoUpdateTypeDelete) {
  273. // 停止拉流
  274. [[ZegoExpressEngine sharedEngine] stopPlayingStream:stream.streamID];
  275. }
  276. }
  277. }
  278. // 房间内流附加信息更新通知
  279. - (void)onRoomStreamExtraInfoUpdate:(NSArray<ZegoStream *> *)streamList roomID:(NSString *)roomID {
  280. }
  281. // 房间附加信息更新通知
  282. - (void)onRoomExtraInfoUpdate:(NSArray<ZegoRoomExtraInfo *> *)roomExtraInfoList roomID:(NSString *)roomID {
  283. }
  284. // 房间 Token 鉴权将要过期的回调通知
  285. - (void)onRoomTokenWillExpire:(int)remainTimeInSecond roomID:(NSString *)roomID {
  286. [[XYVoiceRoomAPIManager new] getRefreshTokenWithRoomId:roomID successHandler:^(ZYLResponseModel *responseModel) {
  287. NSDictionary *authInfo = responseModel.data[@"authInfo"];
  288. if (authInfo) {
  289. NSString *token = authInfo[@"token"];
  290. if (StringIsNotEmpty(token)) {
  291. // 刷新token
  292. [[ZegoExpressEngine sharedEngine] renewToken:token roomID:roomID];
  293. }
  294. }
  295. } failureHandler:^(ZYLNetworkError *error) {
  296. }];
  297. }
  298. // 推流状态回调
  299. - (void)onPublisherStateUpdate:(ZegoPublisherState)state errorCode:(int)errorCode extendedData:(NSDictionary *)extendedData streamID:(NSString *)streamID {
  300. if (state == ZegoPublisherStatePublishing && errorCode == 0) {
  301. NSLog(@"房间正在推流");
  302. !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(0, @"");
  303. }
  304. if (state == ZegoPublisherStateNoPublish && errorCode == 0) {
  305. NSLog(@"房间停止推流");
  306. !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(0, @"");
  307. }
  308. if (errorCode != 0) {
  309. NSLog(@"推流失败errorCode:%d %@", errorCode,extendedData);
  310. !self.chatRoomRTCBlock?:self.chatRoomRTCBlock(errorCode, [NSString stringWithFormat:@"推流失败 %d", errorCode]);
  311. }
  312. }
  313. // 推流质量回调
  314. - (void)onPublisherQualityUpdate:(ZegoPublishStreamQuality *)quality streamID:(NSString *)streamID {
  315. }
  316. // 推流端音频采集首帧回调
  317. - (void)onPublisherCapturedAudioFirstFrame {
  318. }
  319. // 添加/删除转推 CDN 地址状态回调
  320. - (void)onPublisherRelayCDNStateUpdate:(NSArray< ZegoStreamRelayCDNInfo * > *)infoList streamID:(NSString *)streamID {
  321. }
  322. #pragma mark Player Callback
  323. // 拉流状态变更回调
  324. - (void)onPlayerStateUpdate:(ZegoPlayerState)state errorCode:(int)errorCode extendedData:(nullable NSDictionary *)extendedData streamID:(NSString *)streamID {
  325. }
  326. // 拉流质量回调
  327. - (void)onPlayerQualityUpdate:(ZegoPlayStreamQuality *)quality streamID:(NSString *)streamID {
  328. }
  329. // 拉流媒体事件回调
  330. - (void)onPlayerMediaEvent:(ZegoPlayerMediaEvent)event streamID:(NSString *)streamID {
  331. }
  332. // 拉流端音频接收首帧回调
  333. - (void)onPlayerRecvAudioFirstFrame:(NSString *)streamID {
  334. }
  335. // 收到远端流的 SEI 内容
  336. - (void)onPlayerRecvSEI:(NSData *)data streamID:(NSString *)streamID {
  337. }
  338. #pragma mark Mixer Callback
  339. // 混流转推 CDN 状态更新通知
  340. - (void)onMixerRelayCDNStateUpdate:(NSArray<ZegoStreamRelayCDNInfo *> *)infoList taskID:(NSString *)taskID {
  341. }
  342. // 混流中的每条单流的的声浪更新通知
  343. - (void)onMixerSoundLevelUpdate:(NSDictionary<NSNumber *, NSNumber *> *)soundLevels {
  344. }
  345. // 自动混流中的每条单流的的声浪更新通知
  346. - (void)onAutoMixerSoundLevelUpdate:(NSDictionary<NSString *, NSNumber *> *)soundLevels {
  347. }
  348. #pragma mark Device Callback
  349. // 音频设备状态改变
  350. - (void)onAudioDeviceStateChanged:(ZegoDeviceInfo *)deviceInfo updateType:(ZegoUpdateType)updateType deviceType:(ZegoAudioDeviceType)deviceType {
  351. }
  352. // 音频设备音量改变
  353. - (void)onAudioDeviceVolumeChanged:(int)volume deviceType:(ZegoAudioDeviceType)deviceType deviceID:(NSString *)deviceID {
  354. }
  355. // 本地采集音频声浪回调
  356. - (void)onCapturedSoundLevelUpdate:(NSNumber *)soundLevel {
  357. if (self.streamId.length == 0) {
  358. return;
  359. }
  360. if (!self.enableMicrophone) {
  361. // enableAudioCaptureDevice方法在禁止采集音频时声浪会保持最后一次的值,这里做下重置0
  362. soundLevel = [NSNumber numberWithInt:0];
  363. }
  364. // NSLog(@"当前用户的声浪:%@", soundLevel);
  365. dispatch_async(dispatch_get_main_queue(), ^{
  366. if (self.delegate && [self.delegate respondsToSelector:@selector(reportAudioVolumeIndicationOfSpeakers:)]) {
  367. [self.delegate reportAudioVolumeIndicationOfSpeakers:@{self.streamId:soundLevel}];
  368. }
  369. });
  370. }
  371. // 本地采集音频声浪回调 支持版本:2.10.0 及以上。
  372. - (void)onCapturedSoundLevelInfoUpdate:(ZegoSoundLevelInfo *)soundLevelInfo {
  373. }
  374. // 远端拉流音频声浪回调 key:streamId value:volume 0~100
  375. - (void)onRemoteSoundLevelUpdate:(NSDictionary<NSString *, NSNumber *> *)soundLevels {
  376. // NSLog(@"其他用户的声浪:%@", soundLevels);
  377. dispatch_async(dispatch_get_main_queue(), ^{
  378. if (self.delegate && [self.delegate respondsToSelector:@selector(reportAudioVolumeIndicationOfSpeakers:)]) {
  379. [self.delegate reportAudioVolumeIndicationOfSpeakers:soundLevels];
  380. }
  381. });
  382. }
  383. // 远端拉流音频声浪回调 支持版本:2.10.0 及以上。
  384. - (void)onRemoteSoundLevelInfoUpdate:(NSDictionary<NSString *, ZegoSoundLevelInfo *> *)soundLevelInfos {
  385. }
  386. // 本地采集音频频谱回调
  387. - (void)onCapturedAudioSpectrumUpdate:(NSArray<NSNumber *> *)audioSpectrum {
  388. }
  389. // 远端拉流音频频谱回调
  390. - (void)onRemoteAudioSpectrumUpdate:(NSDictionary<NSString *, NSArray<NSNumber *> *> *)audioSpectrums {
  391. }
  392. // 设备异常通知
  393. - (void)onDeviceError:(int)errorCode deviceName:(NSString *)deviceName {
  394. }
  395. // 远端麦克风设备状态通知
  396. - (void)onRemoteMicStateUpdate:(ZegoRemoteDeviceState)state streamID:(NSString *)streamID {
  397. }
  398. // 音频设备路由变更通知
  399. - (void)onAudioRouteChange:(ZegoAudioRoute)audioRoute {
  400. }
  401. // 房间内正在推拉流的用户的网络质量回调
  402. - (void)onNetworkQuality:(NSString *)userID upstreamQuality:(ZegoStreamQualityLevel)upstreamQuality downstreamQuality:(ZegoStreamQualityLevel)downstreamQuality {
  403. }
  404. #pragma mark — 音乐播放管理
  405. - (void)initAudioPlayer {
  406. ZegoMediaPlayer *mediaPlayer = [[ZegoExpressEngine sharedEngine] createMediaPlayer];
  407. if (mediaPlayer) {
  408. [mediaPlayer setEventHandler:self];
  409. // 禁止背景音乐输出
  410. [self.mediaPlayer enableAux:self.enableMicrophone];
  411. self.mediaPlayer = mediaPlayer;
  412. } else {
  413. NSLog(@"创建播放器失败");
  414. }
  415. }
  416. /// 开始播放音乐文件
  417. /// @param filePath 指定需要混音的音频文件名和文件路径名,例如: /var/mobile/Containers/Data/audio.mp4。建议填写文件后缀名。若无法确定文件后缀名,可不填。支持以下音频格式: mp3,aac,m4a,3gp,wav
  418. - (void)startAudioMixing:(NSString * _Nonnull)filePath musicId:(nonnull NSString *)musicId {
  419. if (_mediaPlayer == nil) {
  420. [self initAudioPlayer];
  421. }
  422. if (self.mediaPlayer.currentState == ZegoMediaPlayerStatePlaying) {
  423. [self.mediaPlayer stop];
  424. }
  425. // 设置背景音乐混流状态
  426. [self.mediaPlayer enableAux:self.enableMicrophone];
  427. [self.mediaPlayer loadResource:filePath callback:^(int errorCode) {
  428. if (errorCode == 0) {
  429. self.currentPlayMusicId = [musicId copy];
  430. [self.mediaPlayer start];
  431. }else {
  432. if (self.delegate && [self.delegate respondsToSelector:@selector(playLocalAudioMixingStatusChange:musicId:)]) {
  433. [self.delegate playLocalAudioMixingStatusChange:MusicPlayStatusFailed musicId:musicId];
  434. }
  435. }
  436. }];
  437. }
  438. /// 停止播放音乐文件
  439. - (void)stopAudioMixing {
  440. [self.mediaPlayer stop];
  441. }
  442. /// 暂停播放音乐文件
  443. - (void)pauseAudioMixing {
  444. [self.mediaPlayer pause];
  445. }
  446. /// 恢复播放音乐文件
  447. - (void)resumeAudioMixing {
  448. [self.mediaPlayer resume];
  449. }
  450. /// 调节音乐文件的播放音量 该方法调节混音的音乐文件在本地和远端播放的音量大小。
  451. /// @param volume 音乐文件播放音量范围为 0~200。默认 100 为原始文件音量
  452. - (void)adjustAudioMixingVolume:(int)volume {
  453. // 设置播放器音量
  454. [self.mediaPlayer setVolume:volume];
  455. }
  456. /// 获取音乐文件的本地播放音量
  457. - (int)getAudioMixingPlayoutVolume {
  458. // 获取播放器当前播放音量
  459. return self.mediaPlayer.playVolume;
  460. }
  461. /// 获取音乐文件时长 单位为毫秒
  462. - (int)getAudioMixingDuration {
  463. return (int)self.mediaPlayer.totalDuration;
  464. }
  465. /// 获取音乐文件播放进度,单位为毫秒。
  466. - (int)getAudioMixingCurrentPosition {
  467. return (int)self.mediaPlayer.currentProgress;
  468. }
  469. /// 设置本地混响效果
  470. /// @param soundName 混响效果的名字 不传则说明是关闭
  471. - (void)setLocalVoiceReverbPresetName:(NSString *)soundName {
  472. if (StringIsEmpty(soundName)) {
  473. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetNone];
  474. }else {
  475. if ([soundName isEqualToString:@"小房间"]) {
  476. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetSoftRoom];
  477. }else if ([soundName isEqualToString:@"大房间"]) {
  478. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetLargeRoom];
  479. }else if ([soundName isEqualToString:@"音乐厅"]) {
  480. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetConcertHall];
  481. }else if ([soundName isEqualToString:@"山谷"]) {
  482. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetValley];
  483. }else if ([soundName isEqualToString:@"录音室"]) {
  484. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetRecordingStudio];
  485. }else if ([soundName isEqualToString:@"地下室"]) {
  486. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetBasement];
  487. }else if ([soundName isEqualToString:@"KTV"]) {
  488. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetKTV];
  489. }else if ([soundName isEqualToString:@"演唱会"]) {
  490. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetVocalConcert];
  491. }else if ([soundName isEqualToString:@"流行"]) {
  492. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetPopular];
  493. }else if ([soundName isEqualToString:@"摇滚"]) {
  494. [[ZegoExpressEngine sharedEngine] setReverbPreset:ZegoReverbPresetRock];
  495. }
  496. }
  497. }
  498. #pragma mark - ZegoMediaPlayerEventHandler
  499. /// 播放器播放状态回调
  500. ///
  501. /// @param mediaPlayer 回调的播放器实例
  502. /// @param state 播放器状态
  503. /// @param errorCode 错误码,详情请参考常用错误码文档
  504. - (void)mediaPlayer:(ZegoMediaPlayer *)mediaPlayer stateUpdate:(ZegoMediaPlayerState)state errorCode:(int)errorCode {
  505. MusicPlayStatus playStatus = 0;
  506. switch (state) {
  507. case ZegoMediaPlayerStateNoPlay:
  508. // 播放停止状态
  509. playStatus = MusicPlayStatusStopped;
  510. break;
  511. case ZegoMediaPlayerStatePlaying:
  512. // 正在播放状态
  513. playStatus = MusicPlayStatusPlaying;
  514. break;
  515. case ZegoMediaPlayerStatePausing:
  516. // 暂停状态
  517. playStatus = MusicPlayStatusPaused;
  518. break;
  519. case ZegoMediaPlayerStatePlayEnded:
  520. // 当前曲目播放完成,可执行播放下一首等操作
  521. playStatus = MusicPlayStatusStopped;
  522. break;
  523. }
  524. if (errorCode != 0) {
  525. playStatus = MusicPlayStatusFailed;
  526. }
  527. if (self.delegate && [self.delegate respondsToSelector:@selector(playLocalAudioMixingStatusChange:musicId:)]) {
  528. [self.delegate playLocalAudioMixingStatusChange:playStatus musicId:self.currentPlayMusicId];
  529. }
  530. NSLog(@"播放状态变更:%lu \n播放报错:%ld", (unsigned long)state, (long)errorCode);
  531. }
  532. /// 播放器网络状态事件回调
  533. ///
  534. /// @param mediaPlayer 回调的播放器实例
  535. /// @param networkEvent 网络状态事件
  536. - (void)mediaPlayer:(ZegoMediaPlayer *)mediaPlayer networkEvent:(ZegoMediaPlayerNetworkEvent)networkEvent {
  537. if (networkEvent == ZegoMediaPlayerNetworkEventBufferBegin) {
  538. // 展示 Loading UI
  539. } else if (networkEvent == ZegoMediaPlayerNetworkEventBufferEnded) {
  540. // 关闭 Loading UI
  541. }
  542. }
  543. /// 播放器播放进度回调
  544. ///
  545. /// @param mediaPlayer 回调的播放器实例
  546. /// @param millisecond 进度,单位为毫秒
  547. - (void)mediaPlayer:(ZegoMediaPlayer *)mediaPlayer playingProgress:(unsigned long long)millisecond {
  548. // 更新进度条
  549. }
  550. @end