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通知。

猜你喜欢

转载自blog.csdn.net/lvmaker/article/details/51659847