AVPlayer和AVPlayerViewController
前面在Android上通过VideoView和MediaController实现了一个播放器的,这次我们在iOS上也实现类似的功能。在iOS上对应的有AVPlayer和AVPlayerViewController,和Android上的机制非常像。 AVPlayer是iOS上封装好的一个系统播放器,可以播放本地文件或者网络流媒体文件。只要把URL路径传给他,然后就能播放了,提供paly/pause/seek等基本操作,非常方便。
文件浏览器
和Android一样,我们也希望实现一个文件浏览器的功能,能够指定播放我们自己的文件,这个播放器的功能就更加完善了。在iOS上每个应用有一个沙盒,可以通过iTunes实现文件共享,可以把PC上的文件放到app中。我们可以实现一个文件浏览器然后来查看沙盒中的所有的文件。为了实现这个功能,在Main.Storyboard中创建一个Table View Controller的控件,同时关联到一个TableViewController的类,它继承自UITableViewController。
@interface TableViewController : UITableViewController
@end
在它的实现类中,我们在viewDidLoad函数中加载文件的列表。其中FileManager是一个自定义的辅助类,负责管理我们的文件,基本上它现在就是管理了一个vector的文件列表。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:docDir];
NSString *fileName;
while (fileName = [dirEnum nextObject]) {
fm->AddFile([fileName UTF8String], [[docDir stringByAppendingPathComponent:fileName] UTF8String]);
}
接下来是把整个文件列表在TableView中显示处理,我们只需要处理Table view data source这个接口即可。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return fm->GetSize();
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Configure the cell...
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"w"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"w"];
}
FileDescriptor *fileDes = fm->GetFileDesByIndex((int)(indexPath.row));
cell.textLabel.text = [[NSString alloc] initWithUTF8String:fileDes->fileName];
return cell;
}
播放文件
有了上面的文件浏览器后,我们只需要在TableView中每个item选择的时候,播放对应的文件即可,也就是在tableview的didSelectRowAtIndexPath这个函数中实现。用到了AVPlayer和AVPlayerViewController的功能。
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
FileDescriptor *des = fm->GetFileDesByIndex(int(indexPath.row));
NSURL *url = [[NSURL alloc] initFileURLWithPath:[[NSString alloc] initWithUTF8String:des->filePath]];
AVPlayer *player = [AVPlayer playerWithURL:url];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
[self presentViewController:playerViewController animated:YES completion:^{
[player play];
}];
}
参考
developer.apple.com/documentati… developer.apple.com/documentati…