使用AVPlayer播放本地视频

时间:2016-10-29 10:38:15

标签: ios avplayer

我只是浪费了3个小时,我无法看到我出错的地方。

我尝试播放使用AVPlayer在本地存储的视频。这就是我启动播放器的方式:

- (void)openVideo:(NSURL *)videoURL {

    NSLog(@"Playing video with the url:\n%@", videoURL);
    AVPlayer *player = [AVPlayer playerWithURL:videoURL];

    AVPlayerViewController *playerViewController = [AVPlayerViewController new];
    playerViewController.player = player;
    [self presentViewController:playerViewController animated:YES completion:nil];

}

这是NSURL我传递的信息:

+ (NSURL *)getURL:(NSString *)itemKey withType:(NSString *)itemType {

    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *dataFilePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: [NSString stringWithFormat:@"%@.%@", itemKey, itemType]]];

    NSURL *itemURL;
    if ([[NSFileManager defaultManager] fileExistsAtPath: dataFilePath]){  // if data exists
        itemURL = [NSURL fileURLWithPath:dataFilePath];
    }
    else {
        NSLog(@"The data requested does not exist! Returning an empty url file...");
        itemURL = nil;
    }
    return itemURL;

}

当我运行openVideo时,我得到的输出是:

Playing video with the url:
/var/mobile/Containers/Data/Application/72C35DC4-9EF1-4924-91F4-EDA4BDB6AAD3/Documents/sample.vid

但我一直在关注视频播放器......

{{3}}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

最后想出了问题。我正在下载我的文件并将其存储为NSData,并且必须使用writeToFile并指定正确的扩展名才能正确读取它们。

NSString *saveFilePath; = [NSTemporaryDirectory()stringByAppendingPathComponent:@"temp.mp4"];

[fileData writeToFile:saveFilePath atomically:YES];
NSURL *filepath = [NSURL fileURLWithPath:saveFilePath];
AVPlayer *player = [AVPlayer playerWithURL:filepath];

希望这可以帮助那些人。