iphone - AVPlayer 不是从 NSCachesDirectory 播放?

标签 iphone ios objective-c avplayer avplayerlayer

您好,我正在尝试从 NSCachesDirectory 播放视频文件。 Player 没有从 videoView 层的 NSCachesDirectory 加载文件。

是否可以从缓存目录内存中播放视频? 请建议我...

我试过这个..

NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
NSString *cachesDir    = [myPathList  objectAtIndex:0];   
NSString *songPath = [[NSString alloc] initWithString: [cachesDir stringByAppendingPathComponent:[NSString stringWithFormat:@"Song.%@", downloadURL]]];

NSURL *pathurl = [[NSURL  alloc] initFileURLWithPath:songPath];
NSLog(@"--pathurl---%@",pathurl);
avPlayer =[AVPlayer playerWithURL:pathurl];
self.avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:avPlayer];

if ( !([avPlayer status] == AVPlayerStatusReadyToPlay)   &&  (dataReceivedSoFar.length >10000))
    {

        avPlayerLayer.frame =CGRectMake(0, 0, 320, 450);

        [[self.videoView layer] addSublayer:avPlayerLayer];

        [avPlayer play];

         NSLog(@"Video IS Playing");

        [alert dismissWithClickedButtonIndex:0 animated:YES];

    }

最佳答案

KVO 方法。 添加观察者:

self.player = [AVPlayer playerWithURL:url];
[self.player addObserver:self forKeyPath:@"status" options:0 context:&PlayerStatusContext];

观察值

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context {

    if (context == &PlayerStatusContext) {
        AVPlayer *thePlayer = (AVPlayer *)object;
        if ([thePlayer status] == AVPlayerStatusFailed) {
            NSError *error = [self.player error];
            // Respond to error: for example, display an alert sheet.
            return;
        }
        // Deal with other status change if appropriate.
        if ([thePlayer status] == AVPlayerStatusReadyToPlay) {
            [self play];
        }
    }
    // Deal with other change notifications if appropriate.
    [super observeValueForKeyPath:keyPath ofObject:object
           change:change context:context];
    return;
}

播放:

- (IBAction)play:sender {
    [self.player play];
}

编辑: 正如 awolCZ 所说,AVPlayer 无法播放部分下载的文件。但是您可以使用类似 http://test.com/test.mp3 的 URL。

关于iphone - AVPlayer 不是从 NSCachesDirectory 播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18843265/

相关文章:

objective-c - 隐藏状态栏 : effect on bounds

ios - FitBit 集成,允许权限后 safari 不会重定向到应用程序

ios - 适用于 iOS 应用程序的 CCAvenue 网关集成套件

ios - 正在显示 View 但打印宽度显示为 0

iphone - 如何在不加载整个 View 的情况下重置 UIImageView 中的图像?

ios - 按顺序异步下载图片

objective-c - 自定义 cocoa 对象的默认值

ios - Objective-c 中的循环和异步连接

ios - 在 Xcode 5.1.1 而不是在 Xcode 6 中发现的问题

iphone - UISlider 代码不覆盖 IB 默认值