利用AVFoundation实现Blink拍照和录像的功能

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

github代码

前几天偶然发现一个app叫Blink,闲来无事,纯当练手,于是就尝试下自己实现它的功能.
页面都挺简单的

1.打开相机

- (void)openCamera:(AVCaptureDevicePosition)cameraPostion {
    BOOL hasCamera = ([[AVCaptureDevice devices] count] > );
    if (hasCamera) {
        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        session.sessionPreset = AVCaptureSessionPresetHigh;
       
        AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
        [captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        [captureVideoPreviewLayer setFrame:self.cameraimageView.bounds];
        [self.cameraimageView.layer addSublayer:captureVideoPreviewLayer];
       
        AVCaptureDevice *device = [self getCamera:cameraPostion];
        NSError *error = nil;
       
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
        [session addInput:input];
       
        stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
        NSDictionary *outputSettings = @{ AVVideoCodecKey : AVVideoCodecJPEG};
        [stillImageOutput setoutputSettings:outputSettings];
        [session addOutput:stillImageOutput];
       
        movieOutput = [[AVCaptureMovieFileOutput alloc] init];
        [session addOutput:movieOutput];
       
        [session startRunning];
    }
}

- (AVCaptureDevice *)getCamera:(AVCaptureDevicePosition)cameraPostion {
    NSArray *cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in cameras) {
        if (device.position == cameraPostion)
            return device;
    }
    return [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}

2.获取静态图片

- (void)captureNow {
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in stillImageOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { break; }
    }
    // 取静态图片
    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
              completionHandler: ^(CMSampleBufferRef imageSampleBuffer,NSError *error) {
                  NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
                  NSData *compressedData = [imageData gzippedDataWithCompressionLevel:1.0];
                  NSData *outputData = [compressedData gunzippedData];
                  UIImage *imageT = [[UIImage alloc] initWithData:outputData];
                  _testimageView.image = imageT;
                  _testimageView.hidden = NO;
                  NSFileManager *fileManager = [NSFileManager defaultManager];
                  Nsstring *filePath = [[Nsstring alloc] initWithFormat:@"%@%@",NstemporaryDirectory(),@"main.png"];
                  [fileManager createFileAtPath:filePath contents:imageData attributes:nil];
                 
                  Nsstring *zipFile = [[Nsstring alloc] initWithFormat:@"%@%@",@"main.zip"];
                  ZipArchive *za = [[ZipArchive alloc] init];
                  [za CreateZipFile2:zipFile];
                  [za addFiletoZip:filePath newname:@"main.png"];
              }];
}

3.录像和播放录像

- (IBAction)beginRecord:(id)sender {
    [movieOutput startRecordingToOutputFileURL:[self fileURLWithName:@"main.mp4"] recordingDelegate:self];
}

- (void)stopRecord {
    [movieOutput stopRecording];
}

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
        didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
              fromConnections:(NSArray *)connections
                        error:(NSError *)error {
    BOOL recordedSuccessfully = YES;
    if (error == nil) {
        [self playVideo:outputFileURL];
    }
    if ([error code] != noErr) {
        id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
        if (value) {
            recordedSuccessfully = [value boolValue];
           
        }
    }
}

- (void)playVideo:(NSURL *)url {
    AVPlayer *player = [AVPlayer playerWithURL:url];
    playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
   
    playerLayer.frame = CGRectMake(,160,284);
    playerLayer.position = self.view.center;
    [self.view.layer addSublayer:playerLayer];
   
    playerLayer.masksToBounds = YES;
    playerLayer.cornerRadius = 20;
    playerLayer.borderWidth = 1;
    playerLayer.borderColor = [UIColor grayColor].CGColor;
   
    [player play];
    [[NSNotificationCenter defaultCenter]
                         addobserver:self
                         selector:@selector(removePlayer)
                         name:AVPlayerItemDidplayToEndTimeNotification
                         object:nil];
}

- (void)removePlayer {
    [playerLayer removeFromSuperlayer];
}

看了下它的网络数据格式方面,Blink主要是打包成zip文件,里面包含json,mp4,png文件.
等有空了,把服务器也写一下,或者谁有兴趣可以把它的服务器实现下.

当然Blink还有一些添加好友,分享等的功能,这些细节还是比较好实现的.

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...