1. 程式人生 > >ios獲取所有相簿的視訊並播放

ios獲取所有相簿的視訊並播放

端午節前,把公司的專案忙完了,這幾天開始繼續DDPlayer的開發,熟悉程式碼之後,首先要解決的是:獲取並播放相簿裡面的視訊。
對於相簿中的視訊,我需要關注視訊的名稱、時常、格式、縮圖等資訊,因此,定義了表示視訊資訊的物件。

//AlbumVideoInfo.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface AlbumVideoInfo : NSObject

@property(nonatomic, copy) NSString *name;
@property(nonatomic
, assign) long long size; //Bytes @property(nonatomic, strong) NSNumber *duration; @property(nonatomic, copy) NSString *format; @property(nonatomic, strong) UIImage *thumbnail; @property (nonatomic, strong) NSURL *videoURL; @end //AlbumVideoInfo.m #import "AlbumVideoInfo.h" @implementation AlbumVideoInfo
@end

然後,從相簿load視訊資訊,並儲存在陣列中,相關關鍵函式有:

//載入視訊
- (void)loadVideos{
    ALAssetsLibrary *library1 = [[ALAssetsLibrary alloc] init];
    [library1 enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        if (group) {
            [group setAssetsFilter:[ALAssetsFilter allVideos]]
; [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) { if (result) { AlbumVideoInfo *videoInfo = [[AlbumVideoInfo alloc] init]; videoInfo.thumbnail = [UIImage imageWithCGImage:result.thumbnail]; // videoInfo.videoURL = [result valueForProperty:ALAssetPropertyAssetURL]; videoInfo.videoURL = result.defaultRepresentation.url; videoInfo.duration = [result valueForProperty:ALAssetPropertyDuration]; videoInfo.name = [self getFormatedDateStringOfDate:[result valueForProperty:ALAssetPropertyDate]]; videoInfo.size = result.defaultRepresentation.size; //Bytes videoInfo.format = [result.defaultRepresentation.filename pathExtension]; [_albumVideoInfos addObject:videoInfo]; } }]; } else { //沒有更多的group時,即可認為已經載入完成。 NSLog(@"after load, the total alumvideo count is %ld",_albumVideoInfos.count); dispatch_async(dispatch_get_main_queue(), ^{ [self showAlbumVideos]; }); } } failureBlock:^(NSError *error) { NSLog(@"Failed."); }]; }
//將建立日期作為檔名
-(NSString*)getFormatedDateStringOfDate:(NSDate*)date{

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"]; //注意時間的格式:MM表示月份,mm表示分鐘,HH用24小時制,小hh是12小時制。
    NSString* dateString = [dateFormatter stringFromDate:date];
    return dateString;
}

最後,就是播放視訊,由於相簿視訊不能獲取到絕對地址,而KxMovieViewController初始化的引數只能是NSString型別的path(本地、遠端都可以),我嘗試使用相簿視訊url的absulutstring來初始化它,沒有成功,故改為使用系統自帶的MPMoviePlayerController。相關關鍵程式碼如下:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _albumVideoInfos = [[NSMutableArray alloc] initWithCapacity:50];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playDidChangeNotification:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(playMovieFinishedCallback:)
                                                     name:MPMoviePlayerPlaybackDidFinishNotification
                                                   object:nil];
        //MPMoviePlayerController fullscreen 模式下,點選左上角的done按鈕,會呼叫exitFullScreen通知。
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullScreen:) name: MPMoviePlayerDidExitFullscreenNotification object:nil];
    }
    return self;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    if (row < _albumVideoInfos.count) {
        AlbumVideoInfo *albumVideoInfo = _albumVideoInfos[row];
        if (!_moviePlayer) {
            _moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:albumVideoInfo.videoURL];
        }else{
            [_moviePlayer setContentURL:albumVideoInfo.videoURL];
        }
        _moviePlayer.view.frame = self.view.bounds;
        _moviePlayer.backgroundView.backgroundColor = [UIColor orangeColor];
        [self.view addSubview:_moviePlayer.view];

        _moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
        _moviePlayer.shouldAutoplay = YES;
        _moviePlayer.repeatMode = MPMovieRepeatModeOne;
        [_moviePlayer setFullscreen:YES animated:YES];
        _moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
        [_moviePlayer play];
    }
}

相關通知的處理:

#pragma mark - handle notification

- (void)playDidChangeNotification:(NSNotification *)notification {
    MPMoviePlayerController *moviePlayer = notification.object;
    MPMoviePlaybackState playState = moviePlayer.playbackState;
    if (playState == MPMoviePlaybackStateStopped) {
        NSLog(@"停止");
    } else if(playState == MPMoviePlaybackStatePlaying) {
        NSLog(@"播放");
    } else if(playState == MPMoviePlaybackStatePaused) {
        NSLog(@"暫停");
    }
}

- (void)playMovieFinishedCallback:(NSNotification *)notification{

    NSLog(@"finish");
}

- (void)exitFullScreen:(NSNotification *)notification{

    NSLog(@"exitFullScreen");
    [_moviePlayer stop];
    [_moviePlayer.view removeFromSuperview];
}

OK,重要的事情都說完了,but,在強調一下一個小細節。
//MPMoviePlayerController fullscreen 模式下,點選左上角的done按鈕,會呼叫exitFullScreen通知。