ios 播放视频

新建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

 

原文地址:https://www.cnblogs.com/hanjun/p/2747880.html