我正在开发一个在应用程序启动时加载视频的应用程序。当视频播放并从屏幕上移除时,我观察到一个巨大的混蛋。
我的代码如下:
VideoPlayer.m
-(id)initWithVideo: (CGRect)frame file:(NSString *)videoFile
{
if (self = [super initWithFrame:frame])
{
NSArray *file = [videoFile componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];
NSString *moviePath = [[NSBundle mainBundle] pathForResource:[file objectAtIndex:0] ofType:[file objectAtIndex:1]];
if (nil != moviePath)
{
if (nil != theMovie)
{
[theMovie.view removeFromSuperview];
}
theMovie = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:moviePath]];
theMovie.view.frame = self.bounds;
theMovie.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
theMovie.moviePlayer.controlStyle = MPMovieControlStyleNone;
theMovie.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
theMovie.moviePlayer.fullscreen = NO;
[self addSubview:theMovie.view];
}
}
return self;
}
请指导我错过的地方。
答案 0 :(得分:7)
-(void)prepareMoviePlayer:(NSURL *)moviePath {
self.moviePlayerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:moviePath];
if ([[self.moviePlayerViewController moviePlayer] respondsToSelector:@selector(loadState)]) {
[[self.moviePlayerViewController moviePlayer] setControlStyle:MPMovieControlStyleEmbedded];
[[self.moviePlayerViewController moviePlayer] setFullscreen:NO];
[[self.moviePlayerViewController moviePlayer] prepareToPlay];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayerLoadStateDidChange:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:nil];
}
- (void)moviePlayerLoadStateDidChange:(NSNotification *)notification {
if ([[self.moviePlayerViewController moviePlayer] loadState] == MPMovieLoadStateStalled) {
NSLog(@"Movie Playback Stalled");
} else if([[self.moviePlayerViewController moviePlayer] loadState] != MPMovieLoadStateUnknown) {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerLoadStateDidChangeNotification
object:nil];
[[[self.moviePlayerViewController moviePlayer] view] setFrame:self.view.bounds];
[[self view] addSubview:[[self.moviePlayerViewController moviePlayer] view]];
[[self.moviePlayerViewController moviePlayer] play];
}
}
NSMoviePlayerViewController prepareToPlay方法似乎是关键所在。我还建议添加其他通知来处理播放完成和播放停止。此外,这些代码中的一部分设计用于从窗口的子视图开始工作。