这是我参与8月更文挑战的第27天,活动详情查看:8月更文挑战
我的专栏
前言
这部分呢主要总结下,如何把移动端的摄像头和麦克风采集到的内容,利用RTMP
协议发送到我们之前搭好的服务端。
没有搭建服务端的请看我之前的简书iOS整理 - 关于直播 - 搭建服务端。
好的,下面进入正题。
LFLiveKit
iOS端进行推流的话我用的是 LFLiveKit!
集成
很好用,可以直接通过 CocoaPods 集成进来:
pod 'LFLiveKit'
接着, pod install ,就可以用了。
在推流的 ViewController 中,导入头文件:
#import "LFLiveKit/LFLiveKit.h"
接着,定义我们自己的推流的URL,
#define PUT_Strean @"rtmp://192.168.1.109:1935/zbcs/room"//推流URL
然后,定义 LFLiveSession
和一个预览的 UIView
:
@property (nonatomic, strong) LFLiveSession *session;
@property (nonatomic, strong) UIView *pp;
使用
实现 LFLiveSession
,并定义开启推流和停止推流的方法:
- (LFLiveSession*)session {
if (!_session) {
_session = [[LFLiveSession alloc] initWithAudioConfiguration:[LFLiveAudioConfiguration defaultConfiguration] videoConfiguration:[LFLiveVideoConfiguration defaultConfiguration]];
_session.preView = self.pp;
_session.running = YES;
_session.showDebugInfo = YES;
_session.captureDevicePosition = AVCaptureDevicePositionBack;
_session.delegate = self;
}
return _session;
}
- (void)startLive {
LFLiveStreamInfo *streamInfo = [LFLiveStreamInfo new];
streamInfo.url = [[NSUserDefaults standardUserDefaults] objectForKey:@"putURL"];
[self.session startLive:streamInfo];
}
- (void)stopLive {
[self.session stopLive];
}
处理代理事件
实现 LFLiveSessionDelegate
的代理方法(打印日志等信息,方便我们调试):
//LFLiveSessionDelegate部分
//MARK: - CallBack:
- (void)liveSession:(nullable LFLiveSession *)session liveStateDidChange: (LFLiveState)state {
switch (state) {
case LFLiveReady: NSLog(@"准备"); break;
case LFLivePending: NSLog(@"连接中"); break;
case LFLiveStart: NSLog(@"已连接"); break;
case LFLiveStop:
self.button.selected = NO;
self.button.backgroundColor = [UIColor blueColor];
NSLog(@"已断开"); break;
case LFLiveError:
self.button.selected = NO;
self.button.backgroundColor = [UIColor blueColor];
NSLog(@"出错"); break;
case LFLiveRefresh: NSLog(@"正在刷新"); break;
default: NSLog(@"连接状态改变。"); break;
}
}
- (void)liveSession:(nullable LFLiveSession *)session debugInfo:(nullable LFLiveDebug*)debugInfo {
NSLog(@"debug -- %@", debugInfo);
}
- (void)liveSession:(nullable LFLiveSession*)session errorCode:(LFLiveSocketErrorCode)errorCode {
NSLog(@"连接失败 -- %lu", (unsigned long)errorCode);
self.button.selected = NO;
self.button.backgroundColor = [UIColor blueColor];
}
最后,在你需要开始直播的地方调用开始直播的方法。需要停止直播的地方调用停止直播的方法就可以了。