ReplayKit
Record or stream video from the screen, and audio from the app and microphone.
Overview
Using the ReplayKit
framework, users can record video from the screen, and audio from the app and microphone. They can then share their recordings with other users through email, messages, and social media. You can build app extensions for live broadcasting your content to sharing services. ReplayKit is incompatible with AVPlayer
content.
概述
使用 ReplayKit 框架,用户可以从屏幕上录制视频,并从应用程序内和麦克风录制音频。 然后他们也可以通过电子邮件、消息和社交媒体与其他用户共享他们的录音。 您还可以构建应用扩展程序,共享服务。 注意:ReplayKit 与 AVPlayer 内容不兼容。
ReplayKit 优点:
1、内存、CPU占用极小可以忽略不计
2、录制清晰度和流畅度非常高
3、不需要导入一些SDK包,对APP的负担几乎为0
4、录制代码实现简单
ReplayKit 缺点:
1、不支持AVPlayer播放的视频录制
2、不支持模拟器
3、无法自定义RPPreviewViewController预览视图
4、无法修改录制视频保存路径
5、录制的原始视频清晰度非常高,导致整个视频文件非常大
6、部分机型部分系统录制会有失败的情况,稳定性有待商榷
7、只支持 iOS9.0+ 版本
录屏过程:
1、检测是否有相册权限(后期不需要本地操作录屏可省略)
2、检测是否支持录屏(iOS9.0+)
3、开始录屏
4、结束录屏
5、将录屏保存到相册
6、拿出相册里当前录屏进行压缩处理(压缩规格可修改)
7、压缩后的录屏保存至沙盒后可进行任意操作
部分代码:
1、获取相册权限
- (void)startRecord {
[MXReplayManager mx_getPHAuthorizationStatusBlock:^(BOOL success) {
if (success) {
[self mx_recorderAvailable];
}
}];
}
2、录屏是否可用
// 录屏是否可用
- (void)mx_recorderAvailable {
if ([_recorder isAvailable]) {
[self mx_startCapture];
} else {
NSLog(@"请允许App录制屏幕且使用麦克风(选择第一项),否则无法进行录屏");
}
}
3、开始录屏
// 开始录屏(分系统)
- (void)mx_startCapture {
//是否录麦克风的声音(如果只想要App内的声音,设置为NO即可)
_recorder.microphoneEnabled = NO;
if ([_recorder isRecording]) {
NSLog(@"正在录制...");
} else {
if (@available(iOS 11.0, *)) {
[_recorder startCaptureWithHandler:^(CMSampleBufferRef _Nonnull sampleBuffer, RPSampleBufferType bufferType, NSError * _Nullable error) {
//CMSampleBufferRef 视频+音频原始帧数据 (帧数据处理可参考部分开源直播SDk)
switch (bufferType) {
case RPSampleBufferTypeVideo: //视频
break;
case RPSampleBufferTypeAudioApp: //App内音频
break;
case RPSampleBufferTypeAudioMic: //麦克风音频
break;
default:
break;
}
} completionHandler:^(NSError * _Nullable error) {
}];
} else if (@available(iOS 10.0, *)) {
[_recorder startRecordingWithHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@"启动录屏成功...");
}
}];
} else if (@available(iOS 9.0, *)) {
[_recorder startRecordingWithMicrophoneEnabled:NO handler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@"启动录屏成功...");
}
}];
}
}
}
4、结束录屏
//停止录屏
- (void)stopRecord {
if (@available(iOS 11.0, *)) {
[_recorder stopCaptureWithHandler:^(NSError * _Nullable error) {
}];
} else {
[_recorder stopRecordingWithHandler:^(RPPreviewViewController * _Nullable previewViewController, NSError * _Nullable error) {
NSURL * videoURL = [previewViewController valueForKey:@"movieURL"];
if (!videoURL) {
NSLog(@"录屏失败...");
} else {
//是否需要展示预览界面给用户,自行决定
[self mx_saveVideoToPhoto:videoURL];
}
}];
}
}
5、保存视频至相册
//保存视频至相册
- (void)mx_saveVideoToPhoto:(NSURL *)videoURL {
NSString * videoPath = [videoURL path];
BOOL compatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPath);
if (compatible) {
UISaveVideoAtPathToSavedPhotosAlbum(videoPath, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
}
}
6、保存视频完成之后的回调
//保存视频完成之后的回调
- (void)savedPhotoImage:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"保存视频失败 == %@", error.description);
} else {
//取出这个视频并按创建日期排序
PHFetchOptions * options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult * assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
PHAsset * phasset = [assetsFetchResults lastObject];
if (phasset) {
//视频文件
if (phasset.mediaType == PHAssetMediaTypeVideo) {
PHImageManager * manager = [PHImageManager defaultManager];
[manager requestAVAssetForVideo:phasset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
AVURLAsset * urlAsset = (AVURLAsset *)asset;
[self mx_saveVideoToDocument:urlAsset.URL];
}];
} else {
NSLog(@"未成功保存视频...");
}
} else {
NSLog(@"未成功保存视频...");
}
}
}
7、保存视频至沙盒
//保存视频至沙盒
- (void)mx_saveVideoToDocument:(NSURL *)videoURL {
NSString * outPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[@"mx_test_replay" stringByAppendingString:@".mp4"]];
[MXReplayManager mx_compressQuailtyWithInputURL:videoURL outputURL:[NSURL fileURLWithPath:outPath] blockHandler:^(AVAssetExportSession * _Nonnull session) {
if (session.status == AVAssetExportSessionStatusCompleted) {
NSLog(@"视频已处理好可以对其进行操作");
//处理完的视频是否需要删除?自行决定
} else {
NSLog(@"视频压缩出错...");
}
}];
}
8、压缩视频
+ (void)mx_compressQuailtyWithInputURL:(NSURL *)inputURL
outputURL:(NSURL *)outputURL
blockHandler:(void (^)(AVAssetExportSession * _Nonnull))handler {
AVURLAsset * asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetExportSession * session = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
session.outputURL = outputURL;
session.outputFileType = AVFileTypeMPEG4;
[session exportAsynchronouslyWithCompletionHandler:^(void) {
if (handler) {
handler(session);
}
}];
}
GitHub地址
原创文章,转载请注明出处。