iOSVideo(視訊)

凌浩雨發表於2018-01-25

1. 帶View的播放器

- (IBAction)moviePlayerViewController:(id)sender {
    // 帶View的播放器的控制器
    
    //1. 獲取URL地址
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"Cupid_高清.mp4" withExtension:nil];
    
    //2. 建立帶View的播放器
    MPMoviePlayerViewController *mpVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    
    //3. 模態檢視彈出 --> 模態檢視的切換應該在View完全展示之後進行
    [self presentViewController:mpVC animated:YES completion:nil];
}

2. 不帶View的播放器

#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h>

@interface ViewController ()

@property (nonatomic, strong) MPMoviePlayerController *mpC;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //檢測視訊播放完畢 --> 可以連續播放視訊
    
    //註冊通知監測視訊播放完畢

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerPlaybackDidFinishNotification:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
}

#pragma mark 通知繫結的方法
- (void)moviePlayerPlaybackDidFinishNotification:(NSNotification *)notification
{
    /**
     MPMovieFinishReasonPlaybackEnded,  播放結束
     MPMovieFinishReasonPlaybackError,  播放錯誤
     MPMovieFinishReasonUserExited      退出播放
     */
    
    //1. 獲取通知結束的狀態
    NSInteger movieFinishKey = [notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];
    
    //2. 根據狀態不同來自行填寫邏輯程式碼
    switch (movieFinishKey) {
        case MPMovieFinishReasonPlaybackEnded:
            NSLog(@"播放結束");
            
            // 進行視訊切換 需要兩步
            
            //1. 要想換視訊, 就需要更換地址
            self.mpC.contentURL = [[NSBundle mainBundle] URLForResource:@"Alizee_La_Isla_Bonita.mp4" withExtension:nil];
            
            // 
            [self.mpC play];
            
            break;
            
        case MPMovieFinishReasonPlaybackError:
            NSLog(@"播放錯誤");
            break;
            
        case MPMovieFinishReasonUserExited:
            NSLog(@"退出播放");
            
            // 如果是不帶view的播放器, 那麼播放完畢(退出/錯誤/結束)都應該退出
            [self.mpC.view removeFromSuperview];
            break;
            
        default:
            break;
    }
    
}

- (void)dealloc
{
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (IBAction)moviePlayerController
{
    // 不帶View的播放器的控制器 --> 需要強引用, 設定frame, 新增到view上, 開始播放
    //1. 獲取URL地址
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"Cupid_高清.mp4" withExtension:nil];
    
    //2. 建立不帶View的播放器
    self.mpC = [[MPMoviePlayerController alloc] initWithContentURL:url];
    
    //3. 設定view.frame
    self.mpC.view.frame = CGRectMake(0, 0, 300, 400);
    
    //4. 新增到view上
    [self.view addSubview:self.mpC.view];
    
    //5. 準備播放 --> 規範寫法, 要寫上. 呼叫play方法時, 會自動呼叫此方法
    [self.mpC prepareToPlay];
    
    //6. 開始播放
    [self.mpC play];
    
    //7. 控制模式
    self.mpC.controlStyle = MPMovieControlStyleFullscreen;
    
    /**
     MPMovieControlStyleNone,       // No controls
     MPMovieControlStyleEmbedded,   // 嵌入式的控制 -- 預設
     MPMovieControlStyleFullscreen, // 全屏時的控制樣式
     */

}
@end

3. iOS9 播放視訊

#import "ViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
@implementation ViewController
- (IBAction)playerViewController {
    //1. 獲取URL地址
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"Cupid_高清.mp4" withExtension:nil];
    
    //2. AV播放檢視控制器
    AVPlayerViewController *pVC = [AVPlayerViewController new];
    
    //3. 建立player --> 設定時需要傳入網址
    pVC.player = [AVPlayer playerWithURL:url];
    
    //4. 開始播放
    [pVC.player play];
    
    //5. 模態彈出
    //[self presentViewController:pVC animated:YES completion:nil];
    
    //5. 如果想要自定義播放器的大小,應該自定義 --> 設定frame / 新增到檢視中
    pVC.view.frame = CGRectMake(40, 200, 300, 400);
    [self.view addSubview:pVC.view];
}
@end

4. 視訊截圖

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController


#pragma mark 點選螢幕, 開始截圖
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //1. URL
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"Cupid_高清.mp4" withExtension:nil];
    
    //2. 獲取資源
    AVAsset *asset = [AVAsset assetWithURL:url];
    
    //3. 建立 資源影像生成器
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    //4. 開始生成影像
    
    //Times : 用來表示影片的時間的值
    
    //value: 幀數
    //timescale: 當前視訊的每秒的幀數
    CMTime time = CMTimeMake(60, 1);
    
    NSValue *value = [NSValue valueWithCMTime:time];
    
    [imageGenerator generateCGImagesAsynchronouslyForTimes:@[value] completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        
        //5. 主執行緒中更新UI
        dispatch_sync(dispatch_get_main_queue(), ^{
            self.imageView.image = [UIImage imageWithCGImage:image];
        });
        
    }];
}

@end

6. 視訊錄製

#import "ViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) MPMoviePlayerController *mpC;

@end

@implementation ViewController

- (IBAction)movieClick:(id)sender {
    //1. 判斷是否可用
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        return;
    }
    
    //2. 建立影像選擇器
    UIImagePickerController *picker = [UIImagePickerController new];
    
    //3. 設定型別
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    //4. 設定媒體型別
    picker.mediaTypes = @[(NSString *)kUTTypeMovie];
    
    //5. 設定相機檢測模式
    picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
    
    //6. 設定視訊的質量
    picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
    
    //7. 設定代理
    picker.delegate = self;
    
    //8. 模態彈出
    [self presentViewController:picker animated:YES completion:nil];
}

//UIImagePickerController 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSLog(@"info: %@",info);
    
    //1. 獲取媒體型別
    NSString *mediaTyep = info[UIImagePickerControllerMediaType];
    
    //2. 判斷是否是視訊的媒體型別
    
    id url = info[UIImagePickerControllerMediaURL];
    
    if ([mediaTyep isEqualToString:(NSString *)kUTTypeMovie]) {
        if (self.mpC == nil) {
            self.mpC = [MPMoviePlayerController new];
            self.mpC.view.frame = self.view.bounds;
            [self.view addSubview:self.mpC.view];
        }
        self.mpC.contentURL = url;
        [self.mpC play];
    }
    
    //3. 儲存視訊
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        
        //3.1 建立ALAssetsLibrary物件
        ALAssetsLibrary *assetsLibrary = [ALAssetsLibrary new];
        
        //3.2 呼叫writeVideoAtPathToSavedPhotosAlbum即可
        //前面的URL, 需要傳入要儲存的視訊的URL.
        [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:url completionBlock:nil];
        
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}
@end

7. 視訊壓縮

#import "ViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@end

@implementation ViewController


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //1. 判斷是否可用
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        return;
    }
    
    //2. 建立影像選擇器
    UIImagePickerController *picker = [UIImagePickerController new];
    
    //3. 設定型別
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    
    //4. 設定媒體型別
    picker.mediaTypes = @[(NSString *)kUTTypeMovie];
    
    //5. 設定代理
    picker.delegate = self;
    
    //6. 模態彈出
    [self presentViewController:picker animated:YES completion:nil];
}


#pragma mark 選中視訊的時候, 進行壓縮處理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //1. 獲取媒體型別
    NSString *mediaTyep = info[UIImagePickerControllerMediaType];
    
    //2. 獲取視訊的地址
    id url = info[UIImagePickerControllerMediaURL];
    
    //3. 開始匯出--> 壓縮
    [self exportWithURL:url];
}

- (void)exportWithURL:(NSURL *)url
{
    //1. 獲取資源
    AVAsset *asset = [AVAsset assetWithURL:url];
    
    //2. 根據資源, 建立資源匯出會話物件
    //presetName : 壓縮的大小
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
   
    //3. 設定匯出路徑
    session.outputURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"12345.mov"]];
    
    //4. 設定匯出型別
    session.outputFileType = AVFileTypeQuickTimeMovie;
    
    //5. 開始匯出
    [session exportAsynchronouslyWithCompletionHandler:^{
        NSLog(@"當你看到這句話的時候, 恭喜你已經匯出成功");
    }];
}

@end


相關文章