您好我正在尝试从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];
}
答案 0 :(得分: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];
答案 1 :(得分: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];
}
EDITING:
由于awolCZ表示AVPlayer无法播放部分下载的文件。但您可以使用类似http://test.com/test.mp3
的内容来获取网址。