我正在使用以下代码使用 MPMoviePlayerController 播放视频,但视频未播放。谁能告诉我为什么?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"/one.mp4"];
NSString *mediaPath = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:filePath];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:mediaPath]];
[[moviePlayer view] setFrame:[[self view] bounds]];
[[self view] addSubview: [moviePlayer view]];
moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[moviePlayer play];
最佳答案
这很奇怪,但如果您将 MPMoviePlayerController 设为属性而不是局部变量,它似乎工作正常。似乎在幕后发生了什么。我认为这与ARC有关。你在使用 ARC 吗?
这也是您过度附加路径的问题:
// You've already got the full path to the documents directory here.
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"/one.mp4"];
// Now you're appending the full path to the documents directory to your bundle path
NSString *mediaPath = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:filePath];
当我在模拟器中运行你的代码时,路径如下所示:
/Users/mlong/Library/Application Support/iPhone Simulator/5.1/Applications/8CFB9B94-BD6A-442C-A525-573FE343506D/VidoePlayer.app/Users/mlong/Library/Application Support/iPhone Simulator/5.1/Applications/8CFB9B94-BD6A-442C-A525-573FE343506D/Documents/one.mp4
应该是这样的:
/Users/mlong/Library/Application Support/iPhone Simulator/5.1/Applications/8CFB9B94-BD6A-442C-A525-573FE343506D/Documents/one.mp4
所以只需删除这一行:
NSString *mediaPath = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:filePath];
然后将您的播放器实例化为:
_moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:filePath]];
[[_moviePlayer view] setFrame:[[self view] bounds]];
[[self view] addSubview: [_moviePlayer view]];
_moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[_moviePlayer play];
因此您应该将 MPMoviePlayerController 添加为包含 View Controller 的属性。
关于iphone - 如何使用 MPMoviePlayerController 播放视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10814308/