多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ### 视频的采集 添加头文件 ``` #import <AVFoundation/AVFoundation.h> #import <AVKit/AVKit.h> #import <MobileCoreServices/MobileCoreServices.h> ``` 遵守协议 ``` @interface ViewController ()<UINavigationBarDelegate, UIImagePickerControllerDelegate> ``` <UINavigationBarDelegate, UIImagePickerControllerDelegate>是两个协议。 ` ` 在`@interface ViewController ()`之后定义一个属性 ``` @property (strong, nonatomic)UIImagePickerController *imagePickerCon; ``` 懒加载 ``` //懒加载 - (UIImagePickerController *)imagePickerCon{ if (!_imagePickerCon) { _imagePickerCon = [[UIImagePickerController alloc]init]; //采集源类型 _imagePickerCon.sourceType = UIImagePickerControllerSourceTypeCamera; //媒体类型 _imagePickerCon.mediaTypes = [NSArray arrayWithObjects:(__bridge NSString*)kUTTypeMovie]; //视频质量 _imagePickerCon.videoQuality = UIImagePickerControllerQualityTypeHigh; //设置代理 _imagePickerCon.delegate = self; } return _imagePickerCon; } ``` 添加按钮触发事件 ``` - (IBAction)pickVideo:(UIButton *)sender { //如果摄像头可用,从摄像头采集视频数据 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { [self presentViewController:self.imagePickerCon animated:YES completion:nil]; } } ``` `UIImagePickerControllerDelegate`,可以从这个协议里找到定义的两个回调函数 ``` //采集媒体数据完成的回调处理 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info { //获取媒体类型 NSString *type = info[UIImagePickerControllerMediaType]; //如果是视频类型 if ([type isEqualToString:(__bridge NSString*)kUTTypeMovie]) { NSURL *mediaUrl = info[UIImagePickerControllerMediaURL]; } //回到主界面 [self dismissViewControllerAnimated:YES completion:nil]; } //采集媒体数据取消的回调处理 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { NSLog(@"您预警取消了采集视频"); //回到主界面 [self dismissViewControllerAnimated:YES completion:nil]; } ``` 注意: ``` //回到主界面 [self dismissViewControllerAnimated:YES completion:nil]; 这一句话是代表着视频录制完里之后,会有一个回到主界面的按钮。或者是自动跳转主界面 ``` ### 视频的播放 在`@interface ViewController ()`之后定义一个属性 ``` //播放视频 @property (strong, nonatomic)AVPlayerViewController *player; ``` ### 视频文件路径,播放窗口的大小 懒加载把视频文件路径,窗口大小加载进去 ``` - (AVPlayerViewController *)player { if (!_player) { _player = [[AVPlayerViewController alloc]init]; //创建avplayer对象--视频文件路径 _player.player = [[AVPlayer alloc]initWithURL:mediaUrl]; //播放窗口大小 //全屏播放 [self presentViewController:self animated:YES completion:nil]; } return _player; } ``` `mediaUrl`最后改为定义到类里,方便播放视频到时候取到该值 ``` @interface ViewController ()<UINavigationBarDelegate, UIImagePickerControllerDelegate> { NSURL *mediaUrl; } ``` ### 播放视频文件 添加按钮触发事件 ``` - (IBAction)playVideo:(UIButton *)sender { //播放视频 [self.player.player play]; } ```