iphone - 如何使用 MPMoviePlayerController 播放视频?

标签 iphone objective-c ios mpmovieplayercontroller mpmovieplayer

我正在使用以下代码使用 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/

相关文章:

iphone - 单击 UIAlertView 时崩溃

objective-c - cocoa : how to add an icon to NSTabViewItem using the method drawlabel:inRect in cocoa?

iphone - 从 ALAssetRepresentation 设置 CGImageRef 的最大尺寸

javascript - Webview和手机Safari在渲染页面方面有什么区别吗?

ios - 广告标识符 [IDFA] 使用不当

iphone - 如何在固定时自动显示地点标题?

iphone - NSURLConnection 与委托(delegate) vs initWithContentsOfURL : with Grand Central Dispatch

iphone - 我应该在 ubuntu 上为 iphone-dev 构建 llvm 吗?

ios - 如何在TableView单元格中显示URL图像而不会卡住?

iphone - 在 iPhone 上从 html 文件生成 PDF