从Assets文件夹中打开视频文件并播放

时间:2019-04-09 16:51:02

标签: ios objective-c avplayerviewcontroller

我正在尝试加载添加到资产/视频文件夹内的.mp4文件,但失败。到目前为止,这是我的代码:

- (IBAction)showVideo:(id)sender
{
    NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths1 objectAtIndex:0];
    NSString *strPath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,@"myVideoName.mp4"];
    NSLog(@"strPath %@",strPath);

    NSURL *videosURL = [NSURL fileURLWithPath:strPath];

    AVPlayer *player = [AVPlayer playerWithURL:videosURL];

    // create a player view controller
    AVPlayerViewController *controller = [[AVPlayerViewController alloc] init];
    [self presentViewController:controller animated:YES completion:nil];
    controller.player = player;
    [player play];
}

我认为我在视频文件路径上做错了。 你能帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我替换了这个:

 NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths1 objectAtIndex:0];
    NSString *strPath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,videoName];
    NSLog(@"strPath %@",strPath);

与此:

 NSBundle *mainBundle = [NSBundle mainBundle];
 NSString *myFile = [mainBundle pathForResource: @"videoName" ofType: @"mp4"];