在iOS中从ALAsset检索URL并播放视频

3
我对Obj-C和块的概念还比较陌生。我读了这篇关于从ALAssets检索URL显示图像的帖子:display image from URL retrieved from ALAsset in iPhone 除了能够使用ALAsset框架在UITableView中查看图片文件外,我还想能够播放存储在图片文件夹中的视频。视频资产会像图片一样出现,因此我想能够点击表格中的视频列表并播放它。(换句话说,我想使用Assets Library Framework播放视频)
这可以通过MPMoviePlayerController实现吗?
从上面的帖子中,我得出需要在该函数内获取视频文件的资产URL的代码:
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
    };

如果这是正确的,那么我需要在该函数中放置什么代码才能通过 MPMoviePlayerController 成功播放视频?
只是为了参考,我用于在 UITableView 中显示资产的代码在这里:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = @"id";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }


 [[cell imageView] setImage:[UIImage imageWithCGImage:[[assets objectAtIndex:indexPath.row] thumbnail]]];
 [[cell textLabel] setText:[NSString stringWithFormat:@"Item %d", indexPath.row+1]];

    return cell;
}

这是我的第一篇帖子,如果我发布有误,请见谅。感谢你的帮助。
4个回答

3

好的,我发现可以使用这个代码块来输出资产库地址的日志:

void (^assetEnumerator)(struct ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) 
{

   if(result != nil) {
        NSLog(@"See Asset: %@", result);
        [assets addObject:result];

    }
};

这将输出类似于

"See Asset: ALAsset - Type:Video, URLs:{
    "com.apple.m4v-video" = "assets-library://asset/asset.m4v?id=100&ext=m4v";    "

所以我可以将这个资产库地址发送给MPMoviePlayerController,它就会起作用!

就像这样:

NSString *urlAddress = @"assets-library://asset/asset.m4v?id=100&ext=m4v";
NSURL *theURL = [NSURL URLWithString:urlAddress];
mp =  [[MPMoviePlayerController alloc] initWithContentURL:theURL];
etc...

现在我只需要动态地从ALAsset对象中获取URL字符串,这应该不难解决...希望如此。


3
更加简单
MPMoviePlayerViewController *moviePlayerVC =[[MPMoviePlayerViewController alloc] initWithContentURL:[[asset defaultRepresentation] url]];

5
对我来说这个不起作用。URL 包含类似于 assets-library://asset/asset.MOV?id=12345&ext=mov 的内容。MoviePlayerController 没有显示任何东西。 - Bob Vork

0

@go2的答案是正确的,但MoviePlayerController没有显示任何内容。

所以你还需要添加moviePlayerController.movieSourceType=MPMovieSourceTypeFile;,请参考下面的代码来播放。

MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[moviePlayerController.view setFrame:self.view.frame];
moviePlayerController.movieSourceType=MPMovieSourceTypeFile;
moviePlayerController.fullscreen = YES;
[moviePlayerController play];

0

您可以通过以下方式获取 asseturl

[result defaultRepresentation] url];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接