这一小节我们看看iOS下对多媒体文件的处理。
Assets Library
iOS处理视频必须遵循以下原则:
- iOS下是不允许你直接通过访问文件的方式去访问应用程序以外的资源的,必须使用Asserts库;
- 你可能会理解多媒体包括音频、照片、图片、视频,但Assets库仅允许你处理在Photo这个应用中的资源,也就是照片和视频;
- 这些内容都是分组保存的(在你的‘照片’应用中),并且存在一个默认的组;
- 组内的文件可以过滤;
- 每个资源都有一个url,可以通过url来访问该资源;
Get Assets Library Details
下面是个小例子,我们枚举资源库对象。
- 添加AssetsLibrary.framework;
- 引入AssetsLibray头文件;
- 编写枚举处理:
- (IBAction)getAssetsLibDetailClick:(id)sender {
numberOfGroups = 0;
numberOfAssets = 0;
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
NSUInteger groupTypes = ALAssetsGroupAll;
// 成功枚举回调方法
ALAssetsLibraryGroupsEnumerationResultsBlock resultBlock = ^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
numberOfGroups++;
numberOfAssets += group.numberOfAssets;
NSLog(@"the name of the group is, %@", [group valueForProperty:ALAssetsGroupPropertyName]);
} else {
NSString *msg = [NSString stringWithFormat:@"There are %d groups with %d assets.", numberOfGroups, numberOfAssets];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Assets Status" message:msg delegate:nil cancelButtonTitle:@"okey" otherButtonTitles:nil, nil];
[alert show];
}
};
// 失败回调方法
ALAssetsLibraryAccessFailureBlock failedBlock = ^(NSError *err) {
NSLog(@"Error is %@", [err localizedDescription]);
};
// 根据groupType枚举group,注意是block中是异步处理,所以需要将最后的结果放在group=NO中
[lib enumerateGroupsWithTypes:groupTypes usingBlock:resultBlock failureBlock:failedBlock];
}
PlayVideo
- 添加MediaPlayer库;
- 实现一个MPMoviePlayerViewController的子类:
.h头文件:
#import <UIKit/UIKit.h> #import <MediaPlayer/MediaPlayer.h> @interface MoviePlayerController : MPMoviePlayerViewController @end
.m实现文件:
#import "MoviePlayerController.h" @implementation MoviePlayerController // 6.0之后使用以下两个方法控制横屏、竖屏 - (BOOL)shouldAutorotate { // 支持自动横竖屏切换 return YES; } - (NSUInteger)supportedInterfaceOrientations { // 必须shouldAutorotate返回YES // 返回支持的方向 return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskLandscapeLeft; } // 6.0之前用于控制横、竖 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) { return YES; } return NO; } @end
- 然后调用播放器:
- (IBAction)playMovie:(id)sender { NSString *urlstring = @"http://xxxx.com/ring/Q350_2007861557.3gp"; NSURL *url = [NSURL URLWithString:urlstring]; MPMoviePlayerViewController *playerViewController = [[MoviePlayerController alloc] initWithContentURL:url]; [self presentMoviePlayerViewControllerAnimated:playerViewController]; }
- 即可实现打开播放器全屏播放。