建立Empty Application,添加HomeViewController
HomeViewController.h代碼
#import <UIKit/UIKit.h>#import <MediaPlayer/MediaPlayer.h> @interface HomeViewController : UIViewController{ MPMoviePlayerViewController *playerViewController;} - (IBAction)buttonClicked:(id)sender;
@end
HomeViewController.m代碼
#import "HomeViewController.h" @interface HomeViewController () @end @implementation HomeViewController //當影片播放完畢或者使用者在影片播放時單擊Done按鈕時,調用moviePlayerDidFinish方法,並傳遞了一個MPMoviePlayerController類型的對象,它是MPMoviePlayerViewController類的一個屬性,MPMoviePlayerController是自動被建立的,用於接受命令但我們不能修改它,可以使用它來管理和配置影片的播放。 //在moviePlayerDidFinish方法中擷取到MPMoviePlayerController對象,然後移去NSNotificationCenter的訊息通知,停止影片的播放,移去影片播放視圖,並釋放MPMoviePlayerViewController對象。- (void)moviePlayerDidFinish:(NSNotification *)aNote{ MPMoviePlayerController *player = [aNote object]; [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player]; [player stop]; [self dismissMoviePlayerViewControllerAnimated]; [playerViewController release];} - (IBAction)buttonClicked:(id)sender { /*本地視頻播放 NSString *filePath =[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"movie.mov"]; NSURL *movieURL = [NSURL fileURLWithPath:filePath]; */ //通過http播放視頻檔案 NSURL *movieURL = [NSURL URLWithString:@"http://www.5i-dream.cn/mkovie.mov"]; playerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:[playerViewController moviePlayer]]; [self presentMoviePlayerViewControllerAnimated:playerViewController];//呈現這個影片播放視圖} @end