錄像、錄音和拍照

    現在我們使用的手機,無論是蘋果還是安卓,都能夠錄音、拍照和錄像,而且感覺這是在正常不過的了,不僅如此,現在的手機還能夠修音,修圖在這裏就不介紹了,這裏主要介紹如何實現錄音、拍照和錄像的功能。

一、錄音

     錄音的介紹:使用的框架和音樂播放器一樣使用的AVFoundation

     錄音使用到的類

   (1)AVAudioRecord(輸入)

   (2)相關的設置屬性

 <1>AVNumberOfChannelsKey:通道數

 <2>AVSampleRateKey:採樣率 44100

 <3>AVLinearPCMBitDepthKey:比特率 設置成16 32

 <4>AVEncoderAudioQualityKey:質量

 <5>AVEncoderBitRateKey:比特採樣率 128000

  錄音的步驟

  1、初始化了錄音對象

  2、開始錄音

  3、停止錄音


具體代碼

#import "ViewController.h"

#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<AVAudioRecorderDelegate>

{

    AVAudioRecorder *audionRecorder;

}

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.frame = CGRectMake(100100100100);

    [button setTitle:@"TICK" forState:UIControlStateNormal];

    button.backgroundColor = [UIColor brownColor];

    [button addTarget:self action:@selector(startAudioRecorder:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];

}


- (void)startAudioRecorder:(UIButton *)sender{

    sender.selected = !sender.selected;

    if (sender.selected != YES) {

        [audionRecorder stop];//停止錄音

    }    

//    URL是本地的URLaudioRecorder

    NSString *name = [NSString stringWithFormat:@"%d.aiff",(int)[NSDatedate].timeIntervalSince1970];

    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectoryNSUserDomainMaskYESlastObjectstringByAppendingPathComponent:name];

  //   1、初始化錄音機

    NSError *error;

    audionRecorder = [[AVAudioRecorder allocinitWithURL:[NSURL URLWithString:path] settings:@{AVNumberOfChannelsKey:@2,AVSampleRateKey:@44100,AVLinearPCMBitDepthKey:@32,AVEncoderAudioQualityKey:@(AVAudioQualityMax),AVEncoderBitRateKey:@128000} error:&error];

/*

 AVNumberOfChannelsKey:通道數,通常爲雙聲道 2

 AVSampleRateKey:採樣率 HZ 通常設置爲44100 44.1KHZ

 AVLinearPCMBitDepthKey:比特率,通常爲8 16 24 32

 AVEncoderAudioQualityKey:聲音質量,參數是一個枚舉

 AVAudioQualityMin    = 0,最小的質量

  AVAudioQualityLow    = 0x20,比較低的質量

 AVAudioQualityMedium = 0x40,中間的質量

 AVAudioQualityHigh   = 0x60,高的質量

 AVAudioQualityMax    = 0x7F最好的質量

 AVEncoderBitRateKey:音頻編碼的比特率 單位BPS(傳輸速率)128000bps

 */

    [audionRecorder prepareToRecord];//欲錄音

    [audionRecorder record];//開始錄音

    audionRecorder.delegate = self;

    NSLog(@"%@",path);

}

//錄音結束的時候調用

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{

//    NSLog(@"錄音結束");

    

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectoryNSUserDomainMaskYES)lastObject];

//    文件操作的類

    NSFileManager *fileManager = [NSFileManager defaultManager];

//    獲得當前文件的所有子文件subpathsAtPath

    NSArray *pathList = [fileManager subpathsAtPath:path];

//    NSLog(@"%@",pathList);

//    NSString *path1 = pathList[2];

//    NSLog(@"%@",path1.pathExtension);

    

//    需要只獲得錄音文件

    NSMutableArray *audioPathList = [NSMutableArray array];

//    遍歷所有這個文件夾下面的子文件

    for (NSString *audioPath in pathList) {

//        通過文件的擴展名(尾綴)來區分是不是錄音文件

        if ([audioPath.pathExtension isEqualToString:@"aiff"]) {

//            把篩選出來的文件放到數組,得到所有的音頻wenjian

            [audioPathList addObject:audioPath];

       }

    }

      NSLog(@"%@",audioPathList);

}


錄像和拍照的使用很相似,在這裏就將它們兩個一塊講了
錄像、拍照
錄像和拍照使用的框架是UIKit框架,使用的類是:UIImagePickerController

介紹一些屬性和方法

區分選擇攝像頭還是相冊:sourceType

 UIImagePickerControllerSourceTypePhotoLibrary,

 保存的相冊

 UIImagePickerControllerSourceTypeCamera,攝像頭

 UIImagePickerControllerSourceTypeSavedPhotosAlbum相冊

 

 區分錄像和拍照cameraCaptureMode

  拍照:UIImagePickerControllerCameraCaptureModePhoto

  錄像:UIImagePickerControllerCameraCaptureModeVideo

 

 設置視頻清晰度

 UIImagePickerControllerQualityTypeHigh高清

 UIImagePickerControllerQualityTypeMedium普通

 UIImagePickerControllerQualityTypeLow

 UIImagePickerControllerQualityType 640x480

 UIImagePickerControllerQualityTypeIFrame 1280x720

 UIImagePickerControllerQualityTypeIFrame 960x540

 

 設置視頻最大的持續時間

 videoMaximumDuration 默認最大十分鐘

 

 

 區分前後攝像頭:cameraDevice

 前置:UIImagePickerControllerCameraDeviceFront

 後置:UIImagePickerControllerCameraDeviceRear

 

 是否顯示控制控件:showsCameraControls

 默認YES顯示控制控件

 

 設置拍照:takePicture

 

 錄像:startVideoCapture

 停止:stopVideoCapture

 

 閃光模式:cameraFlashMode,默認自動

 UIImagePickerControllerCameraFlashModeOff  = -1,關閉

 UIImagePickerControllerCameraFlashModeAuto = 0,自動

 UIImagePickerControllerCameraFlashModeOn   = 1

 開啓

 

 設置調用攝像頭視圖頁面 覆蓋視圖

 cameraOverlayView

 

 設置拍照頁面的形態 camereViewTransform

 

 代理:需要導入兩個代理

 @property(nullable,nonatomic,weak)      id <UINavigationControllerDelegate, UIImagePickerControllerDelegate> delegate;

 

 代理方法:不區分錄像和拍照

採集完成之後調用 不區分拍照和錄像

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info;

 採集取消的時候調用

 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker;



具體代碼

#import "ViewController.h"

#import <AVKit/AVKit.h>

#import <AVFoundation/AVFoundation.h>

#import <MobileCoreServices/MobileCoreServices.h>


#define SCREEN_BOUNDS [UIScreen mainScreen].bounds//屏幕尺寸

#define SCREEN_WIDTH CGRectGetWidth([UIScreen mainScreen].bounds)//屏幕寬

#define SCREEN_HEIGHT CGRectGetHeight([UIScreen mainScreen].bounds)//屏幕高


@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

{

    UILabel *lable;//顯示拍照或者錄像的控件

    BOOL isMovie;//判斷攝像的依據

    

    UIImageView *imageView;//顯示拍照錄像結果的視圖

}

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.frame = CGRectMake(100100100100);

    [button setTitle:@"Camera" forState:UIControlStateNormal];

    button.backgroundColor = [UIColor brownColor];

    [button addTarget:self action:@selector(doit) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];

    

    UISwitch *medioSwitch = [[UISwitch allocinitWithFrame:CGRectMake(SCREEN_WIDTH-100505030)];

    [medioSwitch addTarget:self action:@selector(changeMedio:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:medioSwitch];

    

    lable = [[UILabel allocinitWithFrame:CGRectMake(CGRectGetMinX(medioSwitch.frame), CGRectGetMinY(medioSwitch.frame)-305050)];

    lable.textAlignment = NSTextAlignmentCenter;

    lable.textColor = [UIColor purpleColor];

    lable.text = @"拍照";

    [self.view addSubview:lable];

    

    imageView = [[UIImageView allocinitWithFrame:CGRectMake(100150200300)];

    [self.view addSubview:imageView];

}


- (void)changeMedio:(UISwitch *)sender{


    lable.text = sender.isOn != YES ? @"拍照":@"錄像";


    isMovie = sender.isOn;


}


- (void)doit{

    //    創建錄像、拍照對象

    UIImagePickerController *pickImageController = [[UIImagePickerController allocinit];

    if (isMovie == YES) {

        

 //    選擇攝像頭設備

//     默認選擇相冊

    pickImageController.sourceType = UIImagePickerControllerSourceTypeCamera;

    

//    設置選擇錄像

//    默認拍照 選擇cameraCaptureMode錄像,一定要選擇媒體的類型 不然會崩潰

    

//    選擇媒體的類型

//    拍照的時候不選擇媒體類型,不會崩潰,因爲默認設置是kUTTypeImage

//    kUTTypeImage包含在MobileCoreServices框架中

//    MobileCoreServices需要的內容不是OC中字符串的類型,需要強轉

    

//    mediaTypes錄製視頻,類型要選擇movie,因爲movie裏面包含了audiovideo

    pickImageController.mediaTypes = @[(NSString *)kUTTypeMovie];

    

    pickImageController.cameraCaptureMode =  UIImagePickerControllerCameraCaptureModeVideo;

    

     }

//    delegate裏面包含兩個協議

//    UINavigationBarDelegate

//    UIImagePickerControllerDelegate

    pickImageController.delegate = self;

    

    [self presentViewController:pickImageController animated:YES completion:nil];


}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{


    NSLog(@"完成");

    

    NSLog(@">>>>%@",info);

   

    

    if ([info [UIImagePickerControllerMediaTypeisEqualToString:(NSString *)kUTTypeMovie]) {

        NSLog(@"錄像。。。。。");

        

        NSLog(@"******%@",[info[UIImagePickerControllerMediaURLpath]);

        

//        URL轉換成path

        NSString *path = (NSString *)[info[UIImagePickerControllerMediaURLpath];

//        UIImagePickerControllerMediaURL

//        保存視頻到URL

        UISaveVideoAtPathToSavedPhotosAlbum(path, self@selector(video:didFinishSavingWithError:contextInfo:), nil);

    }

    

    if ([info [UIImagePickerControllerMediaType ] isEqualToString:(NSString *)kUTTypeImage]) {

        NSLog(@"拍照了。。。。。");

        

//        UIImagePickerControllerOriginalImage

        

//        NSLog(@"%@",info [UIImagePickerControllerOriginalImage]);

        

        UIImage *finishImage = info[UIImagePickerControllerOriginalImage];

        

        imageView.image = nil;

        imageView.image = finishImage;

      

//        .jpeg的圖片轉換成二進制

     NSData *imageData = UIImageJPEGRepresentation(finishImage, 0.1);

//        .png的圖片轉換成二進制

    NSData *imageData1 = UIImagePNGRepresentation(finishImage);

        

//        通過這個方法將圖片保存到相冊

        UIImageWriteToSavedPhotosAlbum(finishImage, self@selector(image:didFinishSavingWithError:contextInfo:), nil);

    }

 [self dismissViewControllerAnimated:YES completion:nil];

}

//視頻保存到相冊之後調用

- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void*)contextInfo{

    

    AVPlayer *player = [AVPlayer playerWithURL:[NSURL fileURLWithPath:videoPath]];

    

    AVPlayerViewController *palyerVC = [[AVPlayerViewController allocinit];

    

//    [self.view addSubview:palyerVC.view];

    palyerVC.player = player;

    

    [self presentViewController:palyerVC animated:YES completion:nil];

    

    

    [palyerVC.player play];

}

//圖片保存到相冊之後調用

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void*)contextInfo{


    NSLog(@"保存圖片成功");


}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{

    NSLog(@"取消");

    [self dismissViewControllerAnimated:YES completion:nil];

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章