1。实现:
导入: #import <MediaPlayer/MediaPlayer.h>
MPMoviePlayerController:可进行更加全面的视频显示设置,它没使用delegate,而是靠notification system
MPMoviePlayerViewController:可以放入navigationController,简单实现全屏显示,
或是用presentMoviePlayerViewControllerAnimated进行模式窗口全屏显示
e.g.
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h> /* AVAudioSession */
@property (nonatomic, strong)MPMoviePlayerController *moviePlayer;
//监听结束时
- (void) videoHasFinishedPlaying:(NSNotification *)paramNotification{
/* 找出视频停止播放的原因 */
NSNumber *reason = paramNotification.userInfo [MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
if (reason != nil){
NSInteger reasonAsInteger = [reason integerValue];
switch (reasonAsInteger){
case MPMovieFinishReasonPlaybackEnded:{
NSLog(@"The movie ended normally");
break;
}
case MPMovieFinishReasonPlaybackError:{
NSLog(@"An error happened and the movie ended");
break;
}
case MPMovieFinishReasonUserExited:{
NSLog(@" The user exited the player");
break;
}
}
NSLog(@"Finish Reason = %ld", (long)reasonAsInteger);
[self stopPlayingVideo:nil];
}
}
//开始播放视频
- (void) startPlayingVideo:(id)paramSender{
if (self.moviePlayer != nil){
[self stopPlayingVideo:nil];
}
NSBundle *mainBundle = [NSBundle mainBundle];
NSURL *url = [mainBundle URLForResource:@"Sample" withExtension:@"m4v"];
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
if (self.moviePlayer != nil){
/*监听:结束播放 */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoHasFinishedPlaying:)
name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
NSLog(@"Successfully instantiated the movie player.");
/* 播放比例 */
self.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[self.view addSubview:self.moviePlayer.view]; //稍后需removeFromSuperview
[self.moviePlayer setFullscreen:YES animated:NO];
/* 当模拟器有声音,真机无声音时 需在启动播放器之前 加上以下这一句 */
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[self.moviePlayer play];
} else {
NSLog(@"Failed to instantiate the movie player.");
}
}
//停止播放
- (void) stopPlayingVideo:(id)paramSender {
if (self.moviePlayer != nil){
//取消监听
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
[self.moviePlayer stop];
[self.moviePlayer.view removeFromSuperview];
}
}
postscript:
视频必须是H.264 file format