ios - 使用AVPlayer播放本地视频

标签 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

但是我一直在买一个残疾的视频播放器。

enter image description here

我究竟做错了什么?

最佳答案

终于解决了这个问题。我正在下载文件并将其存储为NSData,并且不得不使用writeToFile并指定正确的扩展名才能正确读取它们。

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

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

希望这可以帮助某人。

关于ios - 使用AVPlayer播放本地视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318246/

相关文章:

ios - 为什么 AVPlayer 在 'playbackBufferEmpty' 之后立即以 'playbackLikelyToKeepUp' 状态失败?

ios - MPMoviewcontroller 和 AVPlayer 具有自定义控件

ios - 单独的 UIViewController 上的多个 AVPlayer

ios - ViewController 推送的差异

ios - 具有圆角半径的 UILabel View 在 iOS 17 Beta 上不起作用 - Xcode 15 Beta

iPhone和iPad,播放视频时截图

iOS 10 AVPlayer 不会从没有扩展名且内容类型为视频/mp4 的 URL 流式传输视频

ios - 使用核心图像进行高效下采样

ios - 如何使用 swift 3 在消息应用程序中共享网址和文本

ios - 处理 Realm 事务