我正在尝试从服务器下载mp4文件,然后将其保存在文件中。保存在文件中后,我尝试播放它。当程序运行时,它会在下载文件时暂停,然后在创建MPMoviePlayerController对象时屏幕变黑。 我做了以下。 1.遍历代码并查看NSDAta对象以确保正在加载正确数量的数据。 2.添加一个if([mFile fileExistsAtPath:filename] == true)以确保文件存在。 3.检查所有返回值为零。 我现在被排除在理想之外!
//设置文件名以将其保存并播放 NSFileManager * mFile = [NSFileManager defaultManager]; NSString * filename = [NSHomeDirectory()stringByAppendingPathComponent:@“ted10.dat”];
// load video
NSURL *movieUrl=[[NSURL alloc] initWithString:@"http://www.besttechsolutions.biz/projects/golfflix/ted.mp4"];
NSData *data = [NSData dataWithContentsOfURL:movieUrl];
[data writeToURL:movieUrl atomically:YES];
[mFile createFileAtPath:filename contents: data attributes:nil];
// makse sure file exist
if ( [mFile fileExistsAtPath:filename]==true )
{
// play it
NSURL *fileUrl=[ NSURL fileURLWithPath:filename];
mp=[[MPMoviePlayerController alloc] initWithContentURL: fileUrl];
[mp.view setFrame: self.view.bounds];
[self.view addSubview: mp.view];
if ([mp respondsToSelector:@selector(loadState)])
{
// Set movie player layout
[mp setControlStyle:MPMovieControlStyleFullscreen];
[mp setFullscreen:YES];
// May help to reduce latency
[mp prepareToPlay];
// Register that the load state changed (movie is ready)
}//localhost/Dino/golflix2/Classes/videolist.h
else
{
}
[mp play];
}
答案 0 :(得分:0)
这是您的固定代码:
- (IBAction) doMovie: (id) sender
{
// set up file name to save it under and play it
NSFileManager *mFile= [NSFileManager defaultManager];
NSString *filename=[ NSHomeDirectory() stringByAppendingPathComponent:@"ted10.mp4"];
// load video
NSURL *movieUrl=[[NSURL alloc] initWithString:@"http://www.besttechsolutions.biz/projects/golfflix/ted.mp4"];
NSError *error = NULL;
NSData *data = [NSData dataWithContentsOfURL:movieUrl];
if( [data writeToFile:filename options: NSDataWritingAtomic error: &error] != YES)
{
NSLog( @"error writing data to file %@", filename );
} else {
// make sure file exist
if ( [mFile fileExistsAtPath:filename]==true )
{
// play it
NSURL *fileUrl=[ NSURL fileURLWithPath:filename];
MPMoviePlayerController * mp=[[MPMoviePlayerController alloc] initWithContentURL: fileUrl];
[mp.view setFrame: self.view.bounds];
[self.view addSubview: mp.view];
// Set movie player layout
[mp setControlStyle:MPMovieControlStyleFullscreen];
[mp setFullscreen:YES];
// May help to reduce latency
[mp prepareToPlay];
[mp play];
}
}
}
1)
最重要的是,您最初试图将电影写回远程网址。我认为你真正想做的是写一个本地文件(或缓存)。
2)
文件扩展名(.mp4)向电影播放器提示正在播放的文件类型。 “.dat”太通用了。
3)
说到写入本地文件,请不要将其放在主目录中。找到缓存目录或其他更合适的目录。