一、庫集成
首先,確保在你的 Podfile 中添加依賴:
pod 'GoogleWebRTC'
然后執行 pod install 安裝庫。
二、代碼示例
2.1、權限配置:在 Info.plist 中添加攝像頭、麥克風權限
<!-- 需要在 Info.plist 中添加以下權限 -->
<key>NSCameraUsageDescription</key>
<string>需要訪問攝像頭進行視頻通話</string>
<key>NSMicrophoneUsageDescription</key>
<string>需要訪問麥克風進行語音通話</string>
<key>NSAppTransportSecurity</key>
<dict><key>NSAllowsArbitraryLoads</key><true/>
</dict>
2.2、代碼
核心類oc:WebRTCManager.m
#import "WebRTCManager.h"
#import <AVFoundation/AVFoundation.h>@interface WebRTCManager ()
@property (nonatomic, strong) RTCPeerConnectionFactory *factory;
@property (nonatomic, strong) RTCVideoTrack *localVideoTrack;
@property (nonatomic, strong) RTCAudioTrack *localAudioTrack;
@property (nonatomic, strong) RTCVideoRendererAdapter *localRenderer;
@end@implementation WebRTCManager- (instancetype)initWithDelegate:(id<WebRTCManagerDelegate>)delegate {self = [super init];if (self) {_delegate = delegate;[self setupPeerConnectionFactory];[self setupPeerConnection];}return self;
}// 初始化 PeerConnection 工廠
- (void)setupPeerConnectionFactory {RTCInitializeSSL();_factory = [[RTCPeerConnectionFactory alloc] init];
}// 配置并創建 PeerConnection
- (void)setupPeerConnection {RTCConfiguration *config = [[RTCConfiguration alloc] init];config.iceServers = @[[[RTCIceServer alloc] initWithURLStrings:@[@"stun:stun.l.google.com:19302"]]];RTCOfferAnswerOptions *offerAnswerOptions = [[RTCOfferAnswerOptions alloc] init];offerAnswerOptions.offerToReceiveAudio = YES;offerAnswerOptions.offerToReceiveVideo = YES;RTCMediaConstraints *constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:@[] optionalConstraints:@[]];_peerConnection = [_factory peerConnectionWithConfiguration:config constraints:constraints delegate:self];
}// 初始化本地媒體流
- (void)setupLocalStreamWithVideoView:(UIView *)videoView {// 請求音視頻權限[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {dispatch_async(dispatch_get_main_queue(), ^{if (granted) {[self createLocalMediaStream];[self setupLocalVideoRender:videoView];} else {NSLog(@"需要攝像頭權限才能使用視頻功能");}});}];
}// 創建本地媒體流
- (void)createLocalMediaStream {_localStream = [_factory mediaStreamWithStreamId:@"localStream"];// 創建音頻軌道RTCAudioSource *audioSource = [_factory audioSourceWithConstraints:[self defaultMediaConstraints]];_localAudioTrack = [_factory audioTrackWithSource:audioSource trackId:@"audio0"];[_localStream addAudioTrack:_localAudioTrack];// 創建視頻軌道RTCVideoSource *videoSource = [_factory videoSourceWithConstraints:[self videoConstraints]];_localVideoTrack = [_factory videoTrackWithSource:videoSource trackId:@"video0"];[_localStream addVideoTrack:_localVideoTrack];// 將本地流添加到 PeerConnection[_peerConnection addStream:_localStream];
}// 設置本地視頻渲染
- (void)setupLocalVideoRender:(UIView *)videoView {RTCMTLVideoView *rendererView = [[RTCMTLVideoView alloc] init];rendererView.frame = videoView.bounds;rendererView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;[videoView addSubview:rendererView];_localRenderer = [[RTCVideoRendererAdapter alloc] initWithRenderer:rendererView];[_localVideoTrack addRenderer:_localRenderer];
}// 創建 Offer
- (void)createOffer {RTCOfferAnswerConstraints *constraints = [[RTCOfferAnswerConstraints alloc] init];constraints.mandatoryConstraints = @[[[RTCPair alloc] initWithKey:@"OfferToReceiveAudio" value:@"true"],[[RTCPair alloc] initWithKey:@"OfferToReceiveVideo" value:@"true"]];[_peerConnection createOfferWithConstraints:constraints completionHandler:^(RTCSessionDescription * _Nullable sdp, NSError * _Nullable error) {if (error) {NSLog(@"創建 Offer 失敗: %@", error.localizedDescription);return;}[self.peerConnection setLocalDescriptionWithSessionDescription:sdp completionHandler:^(NSError * _Nullable error) {if (error) {NSLog(@"設置本地描述失敗: %@", error.localizedDescription);return;}// 這里應該將 sdp 發送給信令服務器NSString *offerString = [self sessionDescriptionToString:sdp];NSLog(@"生成 Offer: %@", offerString);// [self.signalingClient sendOffer:offerString];}];}];
}// 處理遠程 Offer
- (void)handleRemoteOffer:(NSString *)offer {RTCSessionDescription *remoteSDP = [self stringToSessionDescription:offer type:RTCSdpTypeOffer];[_peerConnection setRemoteDescriptionWithSessionDescription:remoteSDP completionHandler:^(NSError * _Nullable error) {if (error) {NSLog(@"設置遠程 Offer 失敗: %@", error.localizedDescription);return;}// 創建 Answer[self createAnswer];}];
}// 創建 Answer
- (void)createAnswer {RTCOfferAnswerConstraints *constraints = [[RTCOfferAnswerConstraints alloc] init];[_peerConnection createAnswerWithConstraints:constraints completionHandler:^(RTCSessionDescription * _Nullable sdp, NSError * _Nullable error) {if (error) {NSLog(@"創建 Answer 失敗: %@", error.localizedDescription);return;}[self.peerConnection setLocalDescriptionWithSessionDescription:sdp completionHandler:^(NSError * _Nullable error) {if (error) {NSLog(@"設置本地 Answer 失敗: %@", error.localizedDescription);return;}// 將 Answer 發送給信令服務器NSString *answerString = [self sessionDescriptionToString:sdp];NSLog(@"生成 Answer: %@", answerString);// [self.signalingClient sendAnswer:answerString];}];}];
}// 處理遠程 Answer
- (void)handleRemoteAnswer:(NSString *)answer {RTCSessionDescription *remoteSDP = [self stringToSessionDescription:answer type:RTCSdpTypeAnswer];[_peerConnection setRemoteDescriptionWithSessionDescription:remoteSDP completionHandler:^(NSError * _Nullable error) {if (error) {NSLog(@"設置遠程 Answer 失敗: %@", error.localizedDescription);}}];
}// 處理遠程 ICE 候選者
- (void)handleRemoteICECandidate:(NSString *)candidate {NSDictionary *candidateDict = [NSJSONSerialization JSONObjectWithData:[candidate dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];if (!candidateDict) return;RTCIceCandidate *iceCandidate = [[RTCIceCandidate alloc] initWithSdpMLineIndex:[candidateDict[@"sdpMLineIndex"] integerValue]sdpMid:candidateDict[@"sdpMid"]sdp:candidateDict[@"sdp"]];[_peerConnection addIceCandidate:iceCandidate completionHandler:^(NSError * _Nullable error) {if (error) {NSLog(@"添加遠程 ICE 候選者失敗: %@", error.localizedDescription);}}];
}// 斷開連接
- (void)disconnect {[_peerConnection close];_peerConnection = nil;[_localStream removeAllAudioTracks];[_localStream removeAllVideoTracks];_localStream = nil;
}#pragma mark - RTCPeerConnectionDelegate// 收到遠程媒體流
- (void)peerConnection:(RTCPeerConnection *)peerConnection didAddStream:(RTCMediaStream *)stream {NSLog(@"收到遠程媒體流");if ([self.delegate respondsToSelector:@selector(didReceiveRemoteStream:)] && stream) {[self.delegate didReceiveRemoteStream:stream];}
}// 生成 ICE 候選者
- (void)peerConnection:(RTCPeerConnection *)peerConnection didGenerateIceCandidate:(RTCIceCandidate *)candidate {NSDictionary *candidateDict = @{@"sdpMLineIndex": @(candidate.sdpMLineIndex),@"sdpMid": candidate.sdpMid ?: @"",@"sdp": candidate.sdp};NSData *jsonData = [NSJSONSerialization dataWithJSONObject:candidateDict options:0 error:nil];NSString *candidateString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];// 將 ICE 候選者發送給信令服務器NSLog(@"生成 ICE 候選者: %@", candidateString);// [self.signalingClient sendICECandidate:candidateString];
}#pragma mark - 工具方法// 媒體約束配置
- (RTCMediaConstraints *)defaultMediaConstraints {return [[RTCMediaConstraints alloc] initWithMandatoryConstraints:@[] optionalConstraints:@[]];
}// 視頻約束配置
- (RTCMediaConstraints *)videoConstraints {return [[RTCMediaConstraints alloc] initWithMandatoryConstraints:@[[[RTCPair alloc] initWithKey:@"maxWidth" value:@"1280"],[[RTCPair alloc] initWithKey:@"maxHeight" value:@"720"],[[RTCPair alloc] initWithKey:@"maxFrameRate" value:@"30"]] optionalConstraints:@[]];
}// 將 SessionDescription 轉換為字符串
- (NSString *)sessionDescriptionToString:(RTCSessionDescription *)sdp {NSDictionary *dict = @{@"type": [self sdpTypeToString:sdp.type],@"sdp": sdp.sdp};NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}// 將字符串轉換為 SessionDescription
- (RTCSessionDescription *)stringToSessionDescription:(NSString *)string type:(RTCSdpType)type {NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];return [[RTCSessionDescription alloc] initWithType:type sdp:dict[@"sdp"]];
}// SDP 類型轉換
- (NSString *)sdpTypeToString:(RTCSdpType)type {switch (type) {case RTCSdpTypeOffer: return @"offer";case RTCSdpTypeAnswer: return @"answer";case RTCSdpTypePrAnswer: return @"pranswer";case RTCSdpTypeRollback: return @"rollback";default: return @"";}
}@end
調用OC:ViewController.m
#import "ViewController.h"
#import <WebRTC/WebRTC.h>@interface ViewController ()
@property (nonatomic, strong) WebRTCManager *rtcManager;
@property (nonatomic, strong) UIView *localVideoView;
@property (nonatomic, strong) UIView *remoteVideoView;
@property (nonatomic, strong) UIButton *connectButton;
@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];self.view.backgroundColor = UIColor.whiteColor;[self setupUI];[self setupWebRTC];
}- (void)setupUI {// 本地視頻視圖_localVideoView = [[UIView alloc] init];_localVideoView.backgroundColor = UIColor.lightGrayColor;_localVideoView.translatesAutoresizingMaskIntoConstraints = NO;[self.view addSubview:_localVideoView];// 遠程視頻視圖_remoteVideoView = [[UIView alloc] init];_remoteVideoView.backgroundColor = UIColor.darkGrayColor;_remoteVideoView.translatesAutoresizingMaskIntoConstraints = NO;[self.view addSubview:_remoteVideoView];// 連接按鈕_connectButton = [UIButton buttonWithType:UIButtonTypeSystem];[_connectButton setTitle:@"建立連接" forState:UIControlStateNormal];[_connectButton addTarget:self action:@selector(connectButtonTapped) forControlEvents:UIControlEventTouchUpInside];_connectButton.translatesAutoresizingMaskIntoConstraints = NO;[self.view addSubview:_connectButton];// 布局[NSLayoutConstraint activateConstraints:@[// 本地視頻(右上角小窗口)[_localVideoView topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:20],[_localVideoView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20],[_localVideoView.widthAnchor constraintEqualToConstant:120],[_localVideoView.heightAnchor constraintEqualToConstant:180],// 遠程視頻(全屏)[_remoteVideoView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],[_remoteVideoView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],[_remoteVideoView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],[_remoteVideoView.bottomAnchor constraintEqualToAnchor:self.connectButton.topAnchor constant:-20],// 連接按鈕[_connectButton.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-20],[_connectButton.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],[_connectButton.widthAnchor constraintEqualToConstant:120],[_connectButton.heightAnchor constraintEqualToConstant:44]]];
}- (void)setupWebRTC {_rtcManager = [[WebRTCManager alloc] initWithDelegate:self];[_rtcManager setupLocalStreamWithVideoView:self.localVideoView];
}- (void)connectButtonTapped {[_rtcManager createOffer];
}#pragma mark - WebRTCManagerDelegate// 處理收到的遠程流
- (void)didReceiveRemoteStream:(RTCMediaStream *)stream {dispatch_async(dispatch_get_main_queue(), ^{// 渲染遠程視頻if (stream.videoTracks.count > 0) {RTCVideoTrack *remoteVideoTrack = stream.videoTracks[0];RTCMTLVideoView *rendererView = [[RTCMTLVideoView alloc] init];rendererView.frame = self.remoteVideoView.bounds;rendererView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;[self.remoteVideoView addSubview:rendererView];[remoteVideoTrack addRenderer:[[RTCVideoRendererAdapter alloc] initWithRenderer:rendererView]];}});
}- (void)dealloc {[_rtcManager disconnect];
}@end
代碼說明
這個示例實現了 iOS 平臺上基于 WebRTC 的基本音視頻推拉流功能,主要包含以下部分:
WebRTCManager:核心管理類,負責:
- 初始化 WebRTC 相關組件
- 處理本地音視頻流的捕獲和預覽
- 管理 PeerConnection 連接
- 處理 SDP 交換和 ICE 候選者
ViewController:界面控制器,負責:
- 創建本地和遠程視頻的預覽視圖
- 處理用戶交互(如建立連接)
- 渲染遠程視頻流
三、使用說明
這個示例缺少信令服務器的實現,你需要自己搭建一個信令服務器
在實際使用中,需要將代碼中注釋掉的信令發送部分替換為實際的網絡請求
代碼中的 STUN 服務器使用了 Google 的公共服務器,生產環境中建議使用自己的 STUN/TURN 服務器
四、擴展建議
- 添加錯誤處理和重連機制
- 實現多人通話功能
- 添加視頻質量控制
- 實現屏幕共享功能
- 添加音頻 /video 開關控制
這個示例僅僅提供了基礎的推拉流框架,你可以根據實際需求進行擴展和優化。