3

您好我正在尝试从 NSCachesDirectory 播放视频文件。播放器未从 videoView 层中的 NSCachesDirectory 加载文件。

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

这个我试过了。。

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];

    }
4

2 回答 2

0

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.mp3URL 的东西。

于 2013-09-24T14:18:42.430 回答
0

我不确定 [avPlayer status] == AVPlayerStatusReadyToPlay 在这种情况下是否返回 YES。AVPlayer 加载项目需要一些时间。即使使用 KVO 跟踪 AVPlayer.status 是一种更好的方法,您也应该可以立即播放。

卢卡斯

编辑:尝试这种方式(快速获胜):

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];
avPlayerLayer.frame =CGRectMake(0, 0, 320, 450);

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

[avPlayer play];
于 2013-09-24T13:33:29.013 回答