在上兩篇文章的基礎上,我們初步認識了AV Foundation框架,並且可以利用它完成一些特定的需求,今天,繼續我們的小小的研究。日進一步,不求速成。
通過了解我們知道,AV Foundation可以用來播放和建立基於時間的音視訊資源,並可以精確的處理基於時間的音視訊媒體資料(查詢、建立、編輯及二次編碼),當然也可以在硬體裝置上獲取實時的視訊輸入流或視訊回放等。AV Foundation可以滿足您對媒體資料的大部分處理。
在處理之前,我們需要大致的瞭解下媒體工程軟體裡的相關類。一個工程檔案中有很多軌道,如音訊軌道1,音訊軌道2 …,視訊軌道1,視訊軌道2等,每個軌道里有許多素材,對於每個視訊素材,它可以進行縮放、旋轉等操作,素材庫中的視訊拖到軌道中會分為視訊軌和音訊軌兩個軌道。大致分為以下幾個:
AVAsset:素材庫裡的素材;
AVAssetTrack:素材的軌道;
AVMutableComposition :一個用來合成視訊的工程檔案;
AVMutableCompositionTrack :工程檔案中的軌道,有音訊軌、視訊軌等,裡面可以插入各種對應的素材;
AVMutableVideoCompositionLayerInstruction:視訊軌道中的一個視訊,可以縮放、旋轉等;
AVMutableVideoCompositionInstruction:一個視訊軌道,包含了這個軌道上的所有視訊素材;
AVMutableVideoComposition:管理所有視訊軌道,可以決定最終視訊的尺寸,裁剪需要在這裡進行;
AVAssetExportSession:配置渲染引數並渲染。
AVAsset
AVFoundation使用AVAsset類來表示一個媒體資源,一個AVAsset例項是一個或多個音視訊媒體資料的集合,是一個抽象類。可以使用子類用URL來建立一個asset物件,也可以基於現有的媒體資源創造一個新的媒體資源。下面是AVAsset中的一些屬性,分別對應著視訊的基本資訊,如時長,建立時間等。
1 2 3 4 5 6 7 |
@property (nonatomic, readonly) CMTime duration; @property (nonatomic, readonly) float preferredRate;// 預設速度 @property (nonatomic, readonly) float preferredVolume;// 音量 @property (nonatomic, readonly, nullable) AVMetadataItem *creationDate NS_AVAILABLE(10_8, 5_0);// 視訊的建立時間 |
程式碼是最好的老師,建立一個AVAsset:
1 |
AVAsset *asset = [AVAsset assetWithURL:...]; |
為了建立一個由URL標識的代表任何資源的assert物件,可以使用AVURLAssert,最簡單的是從檔案裡建立一個assert物件:
1 2 |
NSURL *url = ...; AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:url options:nil]; |
AVURLAsset初始化方法的第二個引數使用一個dictionary,這個dictionary裡的唯一一個key是 AVURLAssetPreferPreciseDurationAndTimingKey,它的value是一個boolean型別(用NSValue包裝的物件),這個值表示asset是否提供一個精確的duration。
AVURLAssetPreferPreciseDurationAndTimingKey值為NO(不傳預設為NO),duration會取一個估計值,計算量比較小。反之如果為YES,duration需要返回一個精確值,計算量會比較大,耗時比較長。使用一個預估的duration效率比較高並且對播放來說足夠。如果你想要播放asset,初始化方法傳nil就行了,而不是一個dictionry,或者傳一個以AVURLAssetPreferPreciseDurationAndTimingKeydictionary為key,值為NO的一個dictionary;如果你想把asset加到一個composition中,你需要一個精確的訪問許可權,這時你可以傳一個dictionary,這個dictionary的一組鍵值對為AVURLAssetPreferPreciseDurationAndTimingKey和YES。
1 2 3 |
NSURL *url = ...; NSDictionary *options = @{ AVURLAssetPreferPreciseDurationAndTimingKey : @YES }; AVURLAsset *anAssetToUseInAComposition = [[AVURLAsset alloc] initWithURL:url options:options]; |
從asset中獲取靜態圖片(比如說縮圖),你可以用AVAssetImageGenerator物件。可以用asset初始化一個AVAssetImageGenerator物件,即使asset在初始化的時候沒有可見的track也能成功,所以需要使用tracksWithMediaCharacteristic檢測asset是否有track。generateCGImagesAsynchronouslyForTimes:completionHandler: 方法可以生成一系列圖片,第一個引數是一個包含NSValue型別的陣列,陣列裡每一個物件都是CMTime結構體,表示你想要生成的圖片在視訊中的時間點,第二個引數是一個block,每生成一張圖片都會回撥這個block,這個block提供一個result的引數告訴你圖片是否成功生成或者圖片生成操作是否取消。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
AVURLAsset *asset = [AVURLAsset alloc] initWithURL:... options:nil]; if ([asset tracksWithMediaType:[AVMediaTypeVideo ] count] > 0 ) { AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc]initWithAsset:asset]; generator.appliesPreferredTrackTransform = YES; CMTime time = CMTimeMakeWithSeconds(0, 25); NSValue *timeValue = [NSValue valueWithCMTime:time]; [generator generateCGImagesAsynchronouslyForTimes:@[timeValue] completionHandler:^ (CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) { if (result == AVAssetImageGeneratorSucceeded) { UIImage *captureImage = [UIImage imageWithCGImage:image]; // 成功 do something } else { // 失敗 } }]; } |
AVAssetTrack
一般的視訊至少有2個軌道,一個播放聲音,一個播放畫面。在AVAsset中,可以通過trackId,獲得特定的track。
1 |
- (nullable AVAssetTrack *)trackWithTrackID:(CMPersistentTrackID)trackID; |
除了通過trackID獲得track之外,AVAsset中還提供了其他3中方式獲得track:
1 |
@property (nonatomic, readonly) NSArray *tracks; |
tracks中包含了當前Asset中的所有track,通過遍歷我們可以獲得想要的track。
1 |
- (NSArray *)tracksWithMediaType:(NSString *)mediaType; |
-tracksWithMediaType:方法會根據指定的媒體型別返回一個track陣列,陣列中包含著Asset中所有指定媒體型別的track。如果Asset中沒有這個媒體型別的track,返回一個空陣列。AVMediaFormat中一共定義了8種媒體型別: AVMediaTypeVideo、AVMediaTypeAudio、AVMediaTypeText、AVMediaTypeClosedCaption、AVMediaTypeSubtitle、AVMediaTypeTimecode、AVMediaTypeMetadata、AVMediaTypeMuxed。
1 |
- (NSArray *)tracksWithMediaCharacteristic:(NSString *)mediaCharacteristic; |
-tracksWithMediaCharacteristic:方法會根據指定的媒體特徵返回track陣列,陣列的特性與-tracksWithMediaType:類似,如果Asset中沒有這個媒體特徵的track,返回一個空陣列。AVMediaFormat中一共定義了15種媒體特徵: AVMediaTypeMetadataObject、AVMediaCharacteristicVisual、AVMediaCharacteristicAudible、AVMediaCharacteristicLegible、AVMediaCharacteristicFrameBased、AVMediaCharacteristicIsMainProgramContent、AVMediaCharacteristicIsAuxiliaryContent、AVMediaCharacteristicContainsOnlyForcedSubtitles、AVMediaCharacteristicTranscribesSpokenDialogForAccessibility、AVMediaCharacteristicDescribesMusicAndSoundForAccessibility、AVMediaCharacteristicEasyToRead、AVMediaCharacteristicDescribesVideoForAccessibility、AVMediaCharacteristicLanguageTranslation、AVMediaCharacteristicDubbedTranslation、AVMediaCharacteristicVoiceOverTranslation。
程式碼實現:
1 2 3 4 5 6 7 |
AVAsset *asset = [AVAsset assetWithURL:...]; NSArray* allVideoTracks = [asset tracksWithMediaType:AVMediaTypeVideo]; if ([allVideoTracks count] > 0) { AVAssetTrack* track = [[asset tracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0]; CGSize size = [track naturalSize];// 本視訊的解析度 } |
下面看一個小例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
AVAsset *asset = [AVAsset assetWithURL:...]; AVAssetTrack *videoAssetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0];//素材的視訊軌 AVAssetTrack *audioAssertTrack = [[asset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];//素材的音訊軌 //將素材的視訊插入視訊軌,音訊插入音訊軌 AVMutableComposition *composition = [AVMutableComposition composition];//這是工程檔案 AVMutableCompositionTrack *videoCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];//視訊軌道 [videoCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAssetTrack.timeRange.duration) ofTrack:videoAssetTrack atTime:kCMTimeZero error:nil];//在視訊軌道插入一個時間段的視訊 AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];//音訊軌道 [audioCompositionTrack insertTimeRange: CMTimeRangeMake(kCMTimeZero, videoAssetTrack.timeRange.duration) ofTrack:audioAssertTrack atTime:kCMTimeZero error:nil];//插入音訊資料,否則沒有聲音 // 裁剪視訊 AVMutableVideoCompositionLayerInstruction *videoCompositionLayerIns = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoAssetTrack]; [videoCompositionLayerIns setTransform:videoAssetTrack.preferredTransform atTime:kCMTimeZero];//得到視訊素材 AVMutableVideoCompositionInstruction *videoCompositionIns = [AVMutableVideoCompositionInstruction videoCompositionInstruction]; [videoCompositionIns setTimeRange:CMTimeRangeMake(kCMTimeZero, videoAssetTrack.timeRange.duration)];//得到視訊軌道 AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition]; videoComposition.instructions = @[videoCompositionIns];videoComposition.renderSize = CGSizeMake(...);//裁剪出對應的大小 videoComposition.frameDuration = CMTimeMake(1, 30); // 匯出 AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetMediumQuality]; exporter.videoComposition = videoComposition; exporter.outputURL = [NSURL fileURLWithPath:... isDirectory:YES]; exporter.outputFileType = AVFileTypeMPEG4; exporter.shouldOptimizeForNetworkUse = YES; [exporter exportAsynchronouslyWithCompletionHandler:^{ if (exporter.error) { // 失敗處理 }else{ // 成功 } }]; |
補充上篇錄製視訊的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
#import "ViewController.h" #import #import typedef void(^PropertyChangeBlock) (AVCaptureDevice *captureDevice); @interface ViewController () /** 負責輸入和輸出裝置之間的資料傳遞 */ @property (nonatomic,strong) AVCaptureSession *captureSession; /** 負責從AVCaptureDevice獲得輸入資料 */ @property (nonatomic,strong) AVCaptureDeviceInput *captureDeviceInput; /** 視訊輸出流 */ @property (nonatomic,strong) AVCaptureMovieFileOutput *captureMovieFileOutput; /** 相機拍攝預覽圖層 */ @property (nonatomic,strong) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer; /** 是否允許螢幕旋轉(在錄製螢幕中禁止旋轉) */ @property (nonatomic,assign) BOOL enableRotation; /** 旋轉前大小 */ @property (nonatomic,assign) CGRect *lastBounds; /** 後臺任務標識 */ @property (nonatomic,assign) UIBackgroundTaskIdentifier backgroundTaskIdentifier; @property (weak, nonatomic) IBOutlet UIView *viewContainer; /** 自動閃光按鈕 */ @property (weak, nonatomic) IBOutlet UIButton *flashAutoButton; /** 開啟閃光按鈕 */ @property (weak, nonatomic) IBOutlet UIButton *flashOnButton; /** 關閉閃光按鈕 */ @property (weak, nonatomic) IBOutlet UIButton *flashOffButton; /** 聚焦框 */ @property (weak, nonatomic) IBOutlet UIImageView *focusCursor; /** 拍照按鈕 */ @property (weak, nonatomic) IBOutlet UIButton *takeButton1; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // 初始化會話 _captureSession = [[AVCaptureSession alloc] init]; if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset1280x720]) { // 設定解析度 _captureSession.sessionPreset = AVCaptureSessionPreset1280x720; } // 獲得輸入裝置 AVCaptureDevice *captureDevice = [self getCameraDeviceWithPosition:AVCaptureDevicePositionBack]; // 得道後置攝像頭 if (!captureDevice) { NSLog(@"取得後置攝像頭出現錯誤"); return; } // 新增一個音訊輸入裝置 AVCaptureDevice *audioCaptureDevice = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject]; NSError *error = nil; // 根據輸入裝置初始化輸入物件,用於獲得輸入資料 _captureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:captureDevice error:&error]; if (error) { NSLog(@"取得裝置輸入物件時出錯,錯誤原因:%@",error.localizedDescription); return; } AVCaptureDeviceInput *audioCaptureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioCaptureDevice error:&error]; if (error) { NSLog(@"取得裝置輸入物件時出錯,錯誤原因:%@",error.localizedDescription); return; } // 初始化輸出裝置物件,用於獲得輸出資料 _captureMovieFileOutput = [[AVCaptureMovieFileOutput alloc] init]; // 將裝置輸入新增到會話中 if ([_captureSession canAddInput:_captureDeviceInput]) { [_captureSession addInput:_captureDeviceInput]; [_captureSession addInput:audioCaptureDeviceInput]; AVCaptureConnection *captureConnection=[_captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo]; if ([captureConnection isVideoStabilizationSupported ]) { captureConnection.preferredVideoStabilizationMode=AVCaptureVideoStabilizationModeAuto;//視訊防抖 } } // 將裝置輸出新增到會話中 if ([_captureSession canAddOutput:_captureMovieFileOutput]) { [_captureSession addOutput:_captureMovieFileOutput]; } // 建立視訊預覽層,用於時實展示攝像頭狀態 _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession]; CALayer *layer = self.viewContainer.layer; layer.masksToBounds = YES; // 設定圖層的圓角屬性 _captureVideoPreviewLayer.frame = layer.bounds; _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResize; // 填充模式顯示在layer上 // 將視訊預覽層新增到介面中 [layer insertSublayer:_captureVideoPreviewLayer below:self.focusCursor.layer]; _enableRotation=YES; [self addNotificationToCaptureDevice:captureDevice]; // 給輸入裝置新增通知 [self addGenstureRecognizer]; // 新增手勢 [self setFlashModeButtonStatus]; // 設定閃光燈按鈕狀態 } // 在控制器檢視展示和檢視離開介面時啟動,停止會話 - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self.captureSession startRunning]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self.captureSession stopRunning]; } - (BOOL)shouldAutorotate { return self.enableRotation; } // 旋轉螢幕時調整視訊預覽圖層的方向 - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { AVCaptureConnection *captureConnection = [self.captureVideoPreviewLayer connection]; captureConnection.videoOrientation = (AVCaptureVideoOrientation)toInterfaceOrientation; } // 旋轉後重新設定大小 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { _captureVideoPreviewLayer.frame = self.viewContainer.bounds; } -(void)dealloc{ [self removeNotification]; } #pragma -mark 通知 /** * 給輸入裝置新增通知 * */ - (void)addNotificationToCaptureDevice:(AVCaptureDevice *)captureDevice { //注意新增區域改變捕獲通知必須首先設定裝置允許捕獲 [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) { captureDevice.subjectAreaChangeMonitoringEnabled = YES; }]; NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; // 捕獲區域發生改變 [notificationCenter addObserver:self selector:@selector(areaChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:captureDevice]; } - (void)removeNotificationFromCaptureDevice:(AVCaptureDevice *)captureDevice { NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:captureDevice]; } /** * 移除所有通知 */ -(void)removeNotification{ NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter]; [notificationCenter removeObserver:self]; } -(void)addNotificationToCaptureSession:(AVCaptureSession *)captureSession{ NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter]; //會話出錯 [notificationCenter addObserver:self selector:@selector(sessionRuntimeError:) name:AVCaptureSessionRuntimeErrorNotification object:captureSession]; } /** * 裝置連線成功 * * @param notification 通知物件 */ -(void)deviceConnected:(NSNotification *)notification{ NSLog(@"裝置已連線..."); } /** * 裝置連線斷開 * * @param notification 通知物件 */ -(void)deviceDisconnected:(NSNotification *)notification{ NSLog(@"裝置已斷開."); } /** * 捕獲區域改變 * * @param notification 通知物件 */ -(void)areaChange:(NSNotification *)notification{ NSLog(@"捕獲區域改變..."); } /** * 會話出錯 * * @param notification 通知物件 */ -(void)sessionRuntimeError:(NSNotification *)notification{ NSLog(@"會話發生錯誤."); } #pragma -mark 私有方法 /** * 取得指定位置的攝像頭 * * @param position 攝像頭位置 * * @return 攝像頭裝置 */ -(AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position{ NSArray *cameras= [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; for (AVCaptureDevice *camera in cameras) { if ([camera position] == position) { return camera; } } return nil; } /** * 改變裝置屬性的統一操作方法 * @param propertyChange 屬性改變操作 */ - (void)changeDeviceProperty:(PropertyChangeBlock)propertyChange { AVCaptureDevice *captureDevice = [self.captureDeviceInput device]; NSError *error; //注意改變裝置屬性前一定要首先呼叫lockForConfiguration:呼叫完之後使用unlockForConfiguration方法解鎖 if ([captureDevice lockForConfiguration:&error]) { propertyChange(captureDevice); [captureDevice unlockForConfiguration]; }else{ NSLog(@"設定裝置屬性過程發生錯誤,錯誤資訊:%@",error.localizedDescription); } } /** * 設定閃光燈模式 * * @param flashMode 閃光燈模式 */ -(void)setFlashMode:(AVCaptureFlashMode )flashMode{ [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) { if ([captureDevice isFlashModeSupported:flashMode]) { [captureDevice setFlashMode:flashMode]; } }]; } /** * 設定聚焦模式 * * @param focusMode 聚焦模式 */ -(void)setFocusMode:(AVCaptureFocusMode )focusMode{ [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) { if ([captureDevice isFocusModeSupported:focusMode]) { [captureDevice setFocusMode:focusMode]; } }]; } /** * 設定曝光模式 * * @param exposureMode 曝光模式 */ -(void)setExposureMode:(AVCaptureExposureMode)exposureMode{ [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) { if ([captureDevice isExposureModeSupported:exposureMode]) { [captureDevice setExposureMode:exposureMode]; } }]; } /** * 設定聚焦點 * * @param point 聚焦點 */ -(void)focusWithMode:(AVCaptureFocusMode)focusMode exposureMode:(AVCaptureExposureMode)exposureMode atPoint:(CGPoint)point{ [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) { if ([captureDevice isFocusModeSupported:focusMode]) { [captureDevice setFocusMode:AVCaptureFocusModeAutoFocus]; } if ([captureDevice isFocusPointOfInterestSupported]) { [captureDevice setFocusPointOfInterest:point]; } if ([captureDevice isExposureModeSupported:exposureMode]) { [captureDevice setExposureMode:AVCaptureExposureModeAutoExpose]; } if ([captureDevice isExposurePointOfInterestSupported]) { [captureDevice setExposurePointOfInterest:point]; } }]; } /** * 新增手勢:點按時聚焦 * */ - (void)addGenstureRecognizer { UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScreen:)]; [self.viewContainer addGestureRecognizer:tapGesture]; } - (void)tapScreen:(UITapGestureRecognizer *)tapGesture { CGPoint point= [tapGesture locationInView:self.viewContainer]; NSLog(@"(%f,%f)",point.x,point.y); //將UI座標轉化為攝像頭座標 CGPoint cameraPoint= [self.captureVideoPreviewLayer captureDevicePointOfInterestForPoint:point]; [self setFocusCursorWithPoint:point]; [self focusWithMode:AVCaptureFocusModeAutoFocus exposureMode:AVCaptureExposureModeAutoExpose atPoint:cameraPoint]; } /** * 設定聚焦游標位置 * * @param point 游標位置 */ -(void)setFocusCursorWithPoint:(CGPoint)point{ self.focusCursor.center=point; self.focusCursor.transform=CGAffineTransformMakeScale(1.5, 1.5); self.focusCursor.alpha=1.0; [UIView animateWithDuration:1.0 animations:^{ self.focusCursor.transform=CGAffineTransformIdentity; } completion:^(BOOL finished) { self.focusCursor.alpha=0; }]; } /** * 設定閃光燈按鈕狀態 */ -(void)setFlashModeButtonStatus{ AVCaptureDevice *captureDevice=[self.captureDeviceInput device]; AVCaptureFlashMode flashMode=captureDevice.flashMode; if([captureDevice isFlashAvailable]){ // 如果當前閃光可用(後置攝像頭時閃光燈可用,前置攝像頭時閃光燈不可用) self.flashAutoButton.hidden=NO; self.flashOnButton.hidden=NO; self.flashOffButton.hidden=NO; self.flashAutoButton.enabled=YES; self.flashOnButton.enabled=YES; self.flashOffButton.enabled=YES; switch (flashMode) { case AVCaptureFlashModeAuto: self.flashAutoButton.enabled=NO; break; case AVCaptureFlashModeOn: self.flashOnButton.enabled=NO; break; case AVCaptureFlashModeOff: self.flashOffButton.enabled=NO; break; default: break; } }else{ self.flashAutoButton.hidden=YES; self.flashOnButton.hidden=YES; self.flashOffButton.hidden=YES; } } #pragma mark -按鈕處理 #pragma mark 切換前後攝像頭 - (IBAction)toggleButtonClick1:(UIButton *)sender { // 得到當前的輸入裝置並刪除其上面的通知 AVCaptureDevice *currentDevice=[self.captureDeviceInput device]; AVCaptureDevicePosition currentPosition=[currentDevice position]; [self removeNotificationFromCaptureDevice:currentDevice]; AVCaptureDevice *toChangeDevice; AVCaptureDevicePosition toChangePosition=AVCaptureDevicePositionFront; if (currentPosition==AVCaptureDevicePositionUnspecified||currentPosition==AVCaptureDevicePositionFront) { // 如果當前輸入裝置不是前置攝像頭 toChangePosition=AVCaptureDevicePositionBack; } toChangeDevice=[self getCameraDeviceWithPosition:toChangePosition]; // 取得攝像頭裝置 [self addNotificationToCaptureDevice:toChangeDevice]; // 給裝置加入通知 //獲得要調整的裝置輸入物件 AVCaptureDeviceInput *toChangeDeviceInput=[[AVCaptureDeviceInput alloc]initWithDevice:toChangeDevice error:nil]; //改變會話的配置前一定要先開啟配置,配置完成後提交配置改變 [self.captureSession beginConfiguration]; //移除原有輸入物件 [self.captureSession removeInput:self.captureDeviceInput]; //新增新的輸入物件 if ([self.captureSession canAddInput:toChangeDeviceInput]) { [self.captureSession addInput:toChangeDeviceInput]; self.captureDeviceInput=toChangeDeviceInput; } //提交會話配置 [self.captureSession commitConfiguration]; [self setFlashModeButtonStatus]; } #pragma mark 錄製視訊 - (IBAction)takeButtonClick11:(UIButton *)sender { //根據裝置輸出獲得連線 AVCaptureConnection *captureConnection=[self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo]; //根據連線取得裝置輸出的資料 if (![self.captureMovieFileOutput isRecording]) { // 如果此時沒有在錄屏 self.enableRotation=NO; //如果支援多工則則開始多工 if ([[UIDevice currentDevice] isMultitaskingSupported]) { self.backgroundTaskIdentifier=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil]; } //預覽圖層和視訊方向保持一致 captureConnection.videoOrientation=[self.captureVideoPreviewLayer connection].videoOrientation; NSString *outputFielPath=[NSTemporaryDirectory() stringByAppendingString:@"myMovie.mov"]; NSLog(@"save path is :%@",outputFielPath); NSURL *fileUrl=[NSURL fileURLWithPath:outputFielPath]; NSLog(@"fileUrl:%@",fileUrl); [self.captureMovieFileOutput startRecordingToOutputFileURL:fileUrl recordingDelegate:self]; } else{ [self.captureMovieFileOutput stopRecording];//停止錄製 } } #pragma mark 自動閃光燈開啟 - (IBAction)flashAutoClick1:(UIButton *)sender { [self setFlashMode:AVCaptureFlashModeAuto]; [self setFlashModeButtonStatus]; } #pragma mark 開啟閃光燈 - (IBAction)flashOnClick1:(UIButton *)sender { [self setFlashMode:AVCaptureFlashModeOn]; [self setFlashModeButtonStatus]; } #pragma mark 關閉閃光燈 - (IBAction)flashOffClick1:(UIButton *)sender { [self setFlashMode:AVCaptureFlashModeOff]; [self setFlashModeButtonStatus]; } #pragma mark -AVCaptureFileOutputRecordingDelegate 視訊輸出代理中的方法 // optional // 當資料開始寫入檔案的時候呼叫,如果資料寫入錯誤,則該方法不會被呼叫 - (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections { NSLog(@"開始錄製"); } // required // 當資料寫入完成時呼叫該方法 - (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error { NSLog(@"視訊錄製完成"); //視訊錄製完成之後在後臺將視訊儲存到相簿 self.enableRotation = YES; UIBackgroundTaskIdentifier lastBackgroundTaskIdentifier = self.backgroundTaskIdentifier; self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init]; [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) { if (error) { NSLog(@"儲存視訊到相簿的過程發生錯誤,錯誤資訊:%@",error.localizedDescription); } NSLog(@"outputURL:%@",outputFileURL); [[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil]; if (lastBackgroundTaskIdentifier != UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:lastBackgroundTaskIdentifier]; } NSLog(@"成功儲存視訊到相簿"); }]; } @end |