我正在尝试从服务器下载视频,存储它然后使用AVPlayer
播放它。到目前为止我所拥有的是:
AFNetworking
下载视频数据,并将其NSData
存储在NSDictionary
资源中TargetOverlayView
显示资源内容(图片,文字,播放音频和...视频 - 希望很快)说到显示视频,我写了方法:
(void)playVideo:(NSData*)video{
NSLog(@"TargetOverlayView: playVideo");
if (!video) {
NSLog(@"TargetOV: nothing to play");
[vPlayerLayer removeFromSuperlayer];
vPlayerLayer = nil;
vPlayer = nil;
return;
}
//save nsdata into file
NSLog(@"{SAVE} saving video data into file...");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"video.3gp"]];
[fileManager createFileAtPath:filePath contents:video attributes:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"]];
vPlayer = [[AVPlayer alloc] initWithPlayerItem:playerItem];//[AVPlayer playerWithPlayerItem:playerItem];
vPlayerLayer = [[AVPlayerLayer alloc] init];//[AVPlayerLayer playerLayerWithPlayer:vPlayer];
vPlayerLayer.player = vPlayer;
[vPlayerLayer setFrame:self.frame];
[vPlayerLayer setBackgroundColor:[[UIColor purpleColor] CGColor]];
[self.layer addSublayer:vPlayerLayer];
[vPlayer addObserver:self forKeyPath:@"status" options:0 context:NULL];
}
我还添加了观察者,所以我知道何时播放:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"status"]) {
if (vPlayer.status == AVPlayerStatusReadyToPlay) {
NSLog(@"video ready!");
[vPlayer play];
} else if (vPlayer.status == AVPlayerStatusFailed) {
NSLog(@"vide faield: %@", [vPlayer.error localizedDescription]);
}
}
}
我希望我可以从服务器上下载mp4和3gp视频并播放它们,但只有当我这样做时:http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8 Apple给出了链接它可以工作...我无法设法播放从{{下载的3gp数据1}}(是否可以播放3gp或其他格式?)。有没有办法播放下载的视频?我不需要流媒体(至少现在不是roght)。非常感谢每一个帮助。
编辑: 我改变了一点关于将文件发送到:
filepath
仍然没有工作......
EDIT2: 我在服务器上键入了这个文件的链接 - 然后它工作(只适用于mp4),但我需要下载数据并从中播放视频,而不仅仅是链接到资源......