关于 iOS 10 ReplayKit Live 与 Broadcast UI/Upload Extension

在 iOS 8 及以前,第三方 App 如果想要全局录屏,只能使用私有 API,详见非越狱后台录屏
升级到 iOS 9 后,官方新增了 ReplayKit,并且禁用了录屏的私有 API。ReplayKit 并不算是完美的录屏方案,如果想要把梦幻西游的游戏过程录制下来,需要梦幻西游这个应用本身添加 ReplayKit 的支持,然后再把录制的视频分享出去。对于不支持 ReplayKit 的游戏,怎么录制?答案是,没有办法。试想,又有多少个游戏会内置 ReplayKit 呢?
iOS 10 在 iOS 9 的 ReplayKit 保存录屏视频的基础上,增加了视频流实时直播功能(streaming live),官方介绍见 Go Live with ReplayKit。下面详细说说这个流程。

1. ReplayKit Live 概述

从录制到直播,整体流程如下:
1.被录制端需引入 ReplayKit,发起广播请求。
2.广播端需要实现 Broadcast UI 和 Broadcast Upload 两个 App Extension,以便出现在被录制端的 App 列表。
3.被录制端选定广播端 App 后,开始直播。
其中,被录制端可以是任意一个 App,如梦幻西游,广播端是支持 ReplayKit Live 的直播平台,如虎牙直播。

replaykit_workflow.png

2. 被录制端(游戏或应用)的实现

被录制端需要在原有功能的基础上,增加一个唤起广播的入口。代码:

#import <ReplayKit/ReplayKit.h>

- (IBAction)onLiveButtonPressed:(id)sender { 
     [RPBroadcastActivityViewController loadBroadcastActivityViewControllerWithHandler:^(RPBroadcastActivityViewController * _Nullable broadcastActivityViewController, NSError * _Nullable error) { 
        self.broadcastAVC = broadcastActivityViewController; 
        self.broadcastAVC.delegate = self; 
        [self presentViewController:self.broadcastAVC animated:YES completion:nil]; 
      }];
}

#pragma mark - RPBroadcastActivityViewControllerDelegate

- (void)broadcastActivityViewController:(RPBroadcastActivityViewController *)broadcastActivityViewController didFinishWithBroadcastController:(nullable RPBroadcastController *)broadcastController error:(nullable NSError *)error { 
     [self.broadcastAVC dismissViewControllerAnimated:YES completion:nil]; 
     self.broadcastController = broadcastController; 
     [broadcastController startBroadcastWithHandler:^(NSError * _Nullable error) { 
         if (!error) { 
             self.liveButton.selected = YES; 
         } else { 
             NSLog(@"startBroadcastWithHandler error: %@", error); 
         } 
     }];
}

如下图的右上角就是开始广播的入口按钮。

replaykit_demo_init.png

如果手机内没有支持广播的 App,会弹框提示到 App Store 查找一个。

replaykit_demo_choose.png

如果已经安装支持广播的 App,则会列出,点击后会打开广播端的 Broadcast UI。

replaykit_demo_list.png

下面要说的就是怎么实现一个支持广播的 App。

3. 广播端(直播平台)的实现

很多直播 App 本身已经支持通过摄像头进行视频流上传、直播,新增对 ReplayKit Live 的支持,只需要创建两个扩展的 target,分别是 Broadcast UI Extension 和 Broadcast Upload Extension,在XCode 8 中内置了这两个模板。

3.1 Broadcast UI

Broadcast UI 负责广播前的一些初始化工作,比如,让用户填写直播平台的账号、密码、直播标题。从被录制端唤起广播请求并选定广播平台后,会显示 Broadcast UI 界面。

核心代码:

#import <ReplayKit/ReplayKit.h>

@interface BroadcastViewController : UIViewController

@end

...

- (IBAction)onCancelButtonPressed:(id)sender { 
    [self userDidCancelSetup];
}

- (IBAction)onOKButtonPressed:(id)sender { 
    if (self.accountTextField.text.length == 0 || 
        self.passwordTextField.text.length == 0 || 
        self.channelIDTextField.text.length == 0) { 
        return; 
    } 
    [self userDidFinishSetup];
}

#pragma mark - Private

// Called when the user has finished interacting with the view controller and a broadcast stream can start
- (void)userDidFinishSetup { 
    
    NSLog(@"userDidFinishSetup"); 

    // Broadcast url that will be returned to the application 
    NSURL *broadcastURL = [NSURL URLWithString:@"http://broadcastURL_example/stream1"]; 

    // Service specific broadcast data example which will be supplied to the process extension during broadcast 
    NSDictionary *setupInfo = @{@"account" : self.accountTextField.text, 
                                @"password" : self.passwordTextField.text, 
                                @"channelID" : @(self.channelIDTextField.text.integerValue)}; 

    // Set broadcast settings 
    RPBroadcastConfiguration *broadcastConfig = [[RPBroadcastConfiguration alloc] init]; 
    broadcastConfig.clipDuration = 5.0; // deliver movie clips every 5 seconds 

    // Tell ReplayKit that the extension is finished setting up and can begin broadcasting 
    [self.extensionContext completeRequestWithBroadcastURL:broadcastURL broadcastConfiguration:broadcastConfig setupInfo:setupInfo];
}

- (void)userDidCancelSetup { 

// Tell ReplayKit that the extension was cancelled by the user 
    [self.extensionContext cancelRequestWithError:[NSError errorWithDomain:@"YourAppDomain" code:-1 userInfo:nil]];
}

效果:

replaykit_demo_broadcast_ui.png

如果用户点击 OK
则会回调到第二部分中的RPBroadcastActivityViewControllerDelegate,
开始直播会调用 Broadcast Upload 扩展。

3.2 Broadcast Upload

第二部分调用startBroadcastWithHandler,会跑到Broadcast Upload,本扩展的作用是接收并处理 Broadcast UI 传过来的用户信息,以及处理 RPBroadcastController 传过来的音视频流数据,如编码、上传。

核心代码:

#import <ReplayKit/ReplayKit.h>

@interface SampleHandler : RPBroadcastSampleHandler

@end

...


// To handle samples with a subclass of RPBroadcastSampleHandler set the following in the extension's Info.plist file:
// - RPBroadcastProcessMode should be set to RPBroadcastProcessModeSampleBuffer
// - NSExtensionPrincipalClass should be set to this class

@implementation SampleHandler

- (void)broadcastStartedWithSetupInfo:(NSDictionary<NSString *,NSObject *> *)setupInfo { 

    // User has requested to start the broadcast. Setup info from the UI extension will be supplied. 
    NSLog(@"broadcastStartedWithSetupInfo: %@", setupInfo); 
    [[ReplayKitUploader sharedObject] setupWithInfo:setupInfo];
}

- (void)broadcastPaused { 
    // User has requested to pause the broadcast. Samples will stop being delivered.
}

- (void)broadcastResumed { 
    // User has requested to resume the broadcast. Samples delivery will resume.
}

- (void)broadcastFinished { 
    // User has requested to finish the broadcast.
}

- (void)processSampleBuffer:(CMSampleBufferRef)sampleBuffer withType:(RPSampleBufferType)sampleBufferType { 
    [[ReplayKitUploader sharedObject] handleSampleBuffer:sampleBuffer withType:sampleBufferType];
}

@end

3.3 注意事项

ReplayKitUploader 是自定义的一个类,使用了单例模式,负责广播服务的登录、编码、上传功能。使用单例,而不是直接在 SampleHandler 里面处理,是因为 SampleHandler 并不是 Broadcast Upload Extension 里的唯一一个实例,实际上,Upload Extension 会不断地创建很多个 SampleHandler 来处理 CMSampleBufferRef,而我们为了保存一些内部状态,必须使用一个固定的类实例来实现。

4. App 与 Extension 的代码共用

iOS 10 新增了很多种 Extension,包括本文提到的两种 Broadcast Extension。主 App 与 Extension 属于不同的两个进程,代码逻辑也是分离的,而实际情况中,主 App 与 Extension 往往会包含相同的逻辑,需要共用代码。

主 App 与 Extension 属于两个不同的 target,共用代码,有以下几种方式:

  • 一份代码创建两个副本,分别加到 App 和 Extension 两个 target 中。这种方法简单粗暴而有效,只是,如果需要改动逻辑,则需要改两份代码,想象一下,假如这种改动很频繁,世界上又有几个程序员能受得了?
  • 抽离公共代码,放到独立的 framework,然后两个 target 都依赖该 framework,这是标准而方便的做法。
  • 使用 CocoaPods,只需要在 Podfile 中分别写两个 target 所依赖的 pod 即可,最简洁。

5. 结论

在 iOS 环境中,想要共享设备屏幕,无论是录播还是直播,都注定了没有直接方便的方案。ReplayKit Live 是目前最标准的做法,只是,使用 ReplayKit 有两个前提,应用本身支持 ReplayKit,直播平台支持 Broadcast Extension。这两个前提,后者比较容易实现,而前者,就需要靠各个应用开发商的自觉了。

原文作者:lslin
原文链接:http://blog.lessfun.com/blog/2016/09/21/ios-10-replaykit-live-and-broadcast-extension/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容