如何使用MPMoviePlayerController播放视频?

Per*_*eus 7 iphone objective-c mpmovieplayercontroller mpmovieplayer ios

我使用以下代码使用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];
Run Code Online (Sandbox Code Playgroud)

Mat*_*ong 20

这很奇怪,但是如果你让你的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];
Run Code Online (Sandbox Code Playgroud)

当我在模拟器中运行代码时,路径如下所示:

/ 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 /文档/ 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];
Run Code Online (Sandbox Code Playgroud)

然后将播放器实例化更改为:

_moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:filePath]];

[[_moviePlayer view] setFrame:[[self view] bounds]];
[[self view] addSubview: [_moviePlayer view]];

_moviePlayer.scalingMode = MPMovieScalingModeAspectFit;

[_moviePlayer play];
Run Code Online (Sandbox Code Playgroud)

因此,您应该将MPMoviePlayerController添加为包含视图控制器的属性.