在应用程序中播放Youtube视频很容易,并且有很好的文档支持。
但是,存在两个问题:
- 关闭Youtube播放器后,如果用户想再次播放视频,则必须等待在线流媒体
- 不能离线播放(在家中加载视频以便在路上观看)
是否有人有以下功能的代码:
- 将Youtube视频下载到文档文件夹并显示下载进度
- 通过从文档文件夹加载文件来播放已下载的视频(即使未连接到互联网)
在应用程序中播放Youtube视频很容易,并且有很好的文档支持。
但是,存在两个问题:
是否有人有以下功能的代码:
从YouTube下载视频的方法如下:
NSTemporaryDirectory()
或您的文档目录中的临时命名文件)上打开的 NSOutputStream 或 NSFileHandle。sendSynchronousRequest:returningResponse:error:
。connection:didReceiveResponse:
代理方法中,读取要下载的数据长度以便正确更新进度条。connection:didReceiveData:
代理方法中,将数据写入输出流/文件句柄,并根据需要更新进度条。connectionDidFinishLoading:
或connection:didFailWithError:
中,关闭输出流/文件句柄,并根据需要重命名或删除临时文件。播放视频,只需使用NSURL的fileURLWithPath:
方法创建指向文档目录中本地文件的URL,然后像播放任何远程视频一样进行播放。
我使用了这个项目里的类:https://github.com/larcus94/LBYouTubeView 对我来说它很好用,我可以下载Youtube视频。
我使用了下面这段代码:
LBYouTubeExtractor *extractor = [[[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(@"http://www.youtube.com/watch?v=%@"), self.videoID ]] quality:LBYouTubeVideoQualityLarge] autorelease];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
if(!error) {
NSLog(@"Did extract video URL using completion block: %@", videoURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL: videoURL];
NSString *pathToDocs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = [NSString stringWithFormat:(@"video_%@.mp4"), self.videoID ];
[data writeToFile:[pathTODocs stringByAppendingPathComponent:filename] atomically:YES];
NSLog(@"File %@ successfully saved", filename);
});
} else {
NSLog(@"Failed extracting video URL using block due to error:%@", error);
}
}];