我認(rèn)識(shí)的ReplayKit

工程中用到了琅束,所以小研究了下

一.使用條件
(1)系統(tǒng)版本需要是iOS9.0及以上才支持
(2)模擬器不支持錄屏
(3)[RPScreenRecorder sharedRecorder].available 框架自帶的檢測(cè)機(jī)器硬件等是否支持

二.錄屏方法
1.開(kāi)始錄制

  (1)- (void)startRecordingWithMicrophoneEnabled:(BOOL)microphoneEnabled handler:(nullable void(^)(NSError * _Nullable error))handler可以選擇是否開(kāi)啟麥克風(fēng)
  (2)- (void)startRecordingWithHandler:(nullable void(^)(NSError * _Nullable error))handler
  (3)- (void)startCaptureWithHandler:(nullable void(^)(CMSampleBufferRef sampleBuffer, RPSampleBufferType bufferType, NSError * _Nullable error))captureHandler completionHandler:(nullable void(^)(NSError * _Nullable error))completionHandler iOS才能用的方法茂契,錄制屏幕的時(shí)候可以獲取到流媒體(得到的流媒體可以自己去處理分辨率和格式迫肖,也就是說(shuō)可以直接將流媒體直播出去漩绵,不需要去選擇第三方的直播軟件(前提是你的app有直播功能))sampleBuffer的默認(rèn)格式是420f

2.結(jié)束錄制

(1)- (void)stopRecordingWithHandler:(nullable void(^)(RPPreviewViewController * _Nullable previewViewController, NSError * _Nullable error))handler 與開(kāi)始錄制的(1)(2)對(duì)應(yīng)
previewViewController 是顯示你錄制的內(nèi)容的容器跟磨,錄制結(jié)束需要顯示的錄制內(nèi)容需要如下設(shè)置摩泪,設(shè)置代理可以監(jiān)控保存吼鱼,分享躬贡,返回等


  if (previewViewController) {
                //設(shè)置預(yù)覽頁(yè)面到代理
                previewViewController.previewControllerDelegate = self;
                [self presentViewController:previewViewController animated:YES completion:nil];
            }


(2)- (void)stopCaptureWithHandler:(nullable void(^)(NSError * _Nullable error))handler與開(kāi)始錄制的(3)對(duì)應(yīng)

3.RPScreenRecorderDelegate

(1)- (void)screenRecorder:(RPScreenRecorder *)screenRecorder didStopRecordingWithError:(NSError *)error previewViewController:(nullable RPPreviewViewController *)previewViewController API_DEPRECATED("No longer supported"
(2)- (void)screenRecorder:(RPScreenRecorder *)screenRecorder didStopRecordingWithPreviewViewController:(nullable RPPreviewViewController *)previewViewController error:(nullable NSError *)error 
(3)- (void)screenRecorderDidChangeAvailability:(RPScreenRecorder *)screenRecorder;用來(lái)監(jiān)聽(tīng) ReplayKit 是否可用的谆奥,如果狀態(tài)發(fā)生變化(比如錄制過(guò)程中,切入設(shè)置拂玻,關(guān)閉權(quán)限酸些。)會(huì)回調(diào)該方法

4.RPPreviewViewControllerDelegate

//回放預(yù)覽界面的代理方法
- (void)previewControllerDidFinish:(RPPreviewViewController *)previewController {
    //用戶(hù)操作完成后宰译,返回之前的界面
    [previewController dismissViewControllerAnimated:YES completion:nil];
    
}

//選擇了某些功能的回調(diào)(如分享和保存)
- (void)previewController:(RPPreviewViewController *)previewController didFinishWithActivityTypes:(NSSet <NSString *> *)activityTypes {
 
    __weak ViewController *weakSelf = self;
    if ([activityTypes containsObject:@"com.apple.UIKit.activity.SaveToCameraRoll"]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakSelf showAlert:@"保存成功" andMessage:@"已經(jīng)保存到系統(tǒng)相冊(cè)"];
            [MBProgressHUD showSuccess:@"已經(jīng)保存到系統(tǒng)相冊(cè)"];
        });
    }
    if ([activityTypes containsObject:@"com.apple.UIKit.activity.CopyToPasteboard"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakSelf showAlert:@"復(fù)制成功" andMessage:@"已經(jīng)復(fù)制到粘貼板"];
            [MBProgressHUD showSuccess:@"已經(jīng)復(fù)制到粘貼板"];
        });
    }
}

三.其他

1.(1)檢測(cè)版本
- (BOOL)isSystemVersionOk {
     if ([[UIDevice currentDevice].systemVersion floatValue] < 9.0) {
           return NO;
           } else {
                   return YES;
               }
 }

(2)模擬器
#if TARGET_IPHONE_SIMULATOR
#define SIMULATOR 1
 #elif TARGET_OS_IPHONE
#define SIMULATOR 0
#endif

2.處理流的操作

(1)將視頻幀中的CVPixelBufferRef轉(zhuǎn)img有顏色
-(UIImage*)pixelBuffer2Image:(CVPixelBufferRef) pixelBuffer{
    CIImage *coreImage = [CIImage imageWithCVPixelBuffer:pixelBuffer];
    CIContext *context = [CIContext contextWithOptions:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:kCIContextUseSoftwareRenderer]];//CPU渲染
    CGImageRef cgimg = [context createCGImage:coreImage fromRect:[coreImage extent]];
    UIImage* image = [UIImage imageWithCGImage:cgimg];
    CFRelease(cgimg);
    return image;
}

3.將視頻幀/轉(zhuǎn)換圖片(灰色的我試的是420f格式的)

- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer {
    
    // 為媒體數(shù)據(jù)設(shè)置一個(gè)CMSampleBuffer的Core Video圖像緩存對(duì)象
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    
    if (imageBuffer == nil) {
        return nil;
    }

    // 鎖定pixel buffer的基地址
    CVPixelBufferLockBaseAddress(imageBuffer, 0);

    void *baseAddress = CVPixelBufferGetBaseAddressOfPlane(imageBuffer,0);
//    CVPixelBufferGetBaseAddress(imageBuffer);

    size_t bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer,0);
//    CVPixelBufferGetBytesPerRow(imageBuffer);
    // 得到pixel buffer的寬和高
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    if (width == 0 || height == 0) {return nil;}

    // 創(chuàng)建一個(gè)依賴(lài)于設(shè)備的RGB顏色空間
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    // 用抽樣緩存的數(shù)據(jù)創(chuàng)建一個(gè)位圖格式的圖形上下文(graphics context)對(duì)象
    CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,
                                                 bytesPerRow, colorSpace,kCGImageAlphaNone);


//    CGAffineTransform transform = CGAffineTransformIdentity;
//    CGContextConcatCTM(context, transform);

    // 根據(jù)這個(gè)位圖context中的像素?cái)?shù)據(jù)創(chuàng)建一個(gè)Quartz image對(duì)象
    CGImageRef quartzImage = CGBitmapContextCreateImage(context);

    // 裁剪 圖片
//    struct CGImage *cgImage = CGImageCreateWithImageInRect(quartzImage, CGRectMake(0, 0, height, height));

    // 解鎖pixel buffer
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

    // 釋放context和顏色空間
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    // 用Quartz image創(chuàng)建一個(gè)UIImage對(duì)象image
    UIImage *image = [UIImage imageWithCGImage:quartzImage];

    // 釋放Quartz image對(duì)象
//    CGImageRelease(cgImage);
    CGImageRelease(quartzImage);

    return (image);
    
}

4.流數(shù)據(jù)轉(zhuǎn)成MP4

- (void)startScreenRecording {
 
    self.screenRecorder = [RPScreenRecorder sharedRecorder];
    if (self.screenRecorder.isRecording) {
        return;
    }
    NSError *error = nil;
    NSArray *pathDocuments = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *outputURL = pathDocuments[0];
    
    NSString *videoOutPath = [[outputURL stringByAppendingPathComponent:[NSString stringWithFormat:@"%u", arc4random() % 1000]] stringByAppendingPathExtension:@"mp4"];
    self.assetWriter = [AVAssetWriter assetWriterWithURL:[NSURL fileURLWithPath:videoOutPath] fileType:AVFileTypeMPEG4 error:&error];
    
    NSDictionary *compressionProperties =
  @{
    AVVideoAverageBitRateKey       :  [NSNumber numberWithDouble:2000 * 1000],
    };
    
    NSNumber* width= [NSNumber numberWithFloat:self.view.frame.size.width];
    NSNumber* height = [NSNumber numberWithFloat:self.view.frame.size.height];
    NSDictionary *videoSettings =
  @{
    AVVideoCompressionPropertiesKey : compressionProperties,
    AVVideoCodecKey                 : AVVideoCodecH264,
    AVVideoWidthKey                 : width,
    AVVideoHeightKey                : height};
    
    
    self.assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
    self.assetWriterInput.expectsMediaDataInRealTime = YES;
    if ([self.assetWriter canAddInput:self.assetWriterInput]) {
        [self.assetWriter addInput:self.assetWriterInput];
//        videoQueue = dispatch_queue_create("AVAssetWriter.videoprocessVideoQueue", DISPATCH_QUEUE_SERIAL);
    }
    
    [self.screenRecorder startCaptureWithHandler:^(CMSampleBufferRef  _Nonnull sampleBuffer, RPSampleBufferType bufferType, NSError * _Nullable error) {
        if (CMSampleBufferDataIsReady(sampleBuffer)) {
            if (self.assetWriter.status == AVAssetWriterStatusUnknown && bufferType == RPSampleBufferTypeVideo) {
                
                [self.assetWriter startWriting];
                //丟掉無(wú)用幀
                CMTime pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
                int64_t videopts  = CMTimeGetSeconds(pts) * 1000;
                if(videopts < 0)
                    return ;
//                if(lastVideoPts != videopts)
//                    lastVideoPts = videopts;
//                else
//                    return ;

                [self.assetWriter startSessionAtSourceTime:pts];
//                startTime = CFAbsoluteTimeGetCurrent();
            }
            
            if (self.assetWriter.status == AVAssetWriterStatusFailed) {
                NSLog(@"An error occured.");
                [[RPScreenRecorder sharedRecorder] stopCaptureWithHandler:^(NSError * _Nullable error) {}];
                return;
            }
            if (bufferType == RPSampleBufferTypeVideo) {
                if (self.assetWriterInput.isReadyForMoreMediaData) {
                    
//                    CFRetain(sampleBuffer);
//                    dispatch_async(videoQueue, ^{
                        //將sampleBuffer添加進(jìn)視頻輸入源
                        [self.assetWriterInput appendSampleBuffer:sampleBuffer];

//                    });
//                    CFRelease(sampleBuffer);
                }else{
                    NSLog(@"Not ready for video");
                }
            }
        }
    } completionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@"Recording started successfully.");
        }else{
            NSLog(@"Recording started error %@",error);
        }
    }];
}

初學(xué)者,還有好多地方不懂魄懂,只能把我理解的寫(xiě)下來(lái),請(qǐng)多指教

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末沿侈,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子市栗,更是在濱河造成了極大的恐慌肋坚,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件肃廓,死亡現(xiàn)場(chǎng)離奇詭異智厌,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)盲赊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)铣鹏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人哀蘑,你說(shuō)我怎么就攤上這事诚卸。” “怎么了绘迁?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,764評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵合溺,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我缀台,道長(zhǎng)棠赛,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,193評(píng)論 1 292
  • 正文 為了忘掉前任膛腐,我火速辦了婚禮睛约,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘哲身。我一直安慰自己辩涝,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,216評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布勘天。 她就那樣靜靜地躺著怔揩,像睡著了一般。 火紅的嫁衣襯著肌膚如雪脯丝。 梳的紋絲不亂的頭發(fā)上商膊,一...
    開(kāi)封第一講書(shū)人閱讀 51,182評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音巾钉,去河邊找鬼翘狱。 笑死秘案,一個(gè)胖子當(dāng)著我的面吹牛砰苍,可吹牛的內(nèi)容都是我干的潦匈。 我是一名探鬼主播,決...
    沈念sama閱讀 40,063評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼赚导,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼茬缩!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起吼旧,我...
    開(kāi)封第一講書(shū)人閱讀 38,917評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤凰锡,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后圈暗,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體掂为,經(jīng)...
    沈念sama閱讀 45,329評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,543評(píng)論 2 332
  • 正文 我和宋清朗相戀三年员串,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了勇哗。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,722評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡寸齐,死狀恐怖欲诺,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情渺鹦,我是刑警寧澤扰法,帶...
    沈念sama閱讀 35,425評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站毅厚,受9級(jí)特大地震影響塞颁,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜吸耿,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,019評(píng)論 3 326
  • 文/蒙蒙 一殴边、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧珍语,春花似錦锤岸、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,671評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至募逞,卻和暖如春蛋铆,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背放接。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,825評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工刺啦, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人纠脾。 一個(gè)月前我還...
    沈念sama閱讀 47,729評(píng)論 2 368
  • 正文 我出身青樓玛瘸,卻偏偏與公主長(zhǎng)得像蜕青,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子糊渊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,614評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容