利用MPMoviePlayerViewController 播放視頻 iOS


方法一:

@property (nonatomic, strong) MPMoviePlayerController *player;

    NSString *url = [[NSBundle mainBundle] pathForResource:@"zz_video" ofType:@"mp4"];
    self.player = [[MPMoviePlayerController alloc]
                   initWithContentURL: [NSURL fileURLWithPath:url]];
    self.player.controlStyle = MPMovieControlStyleNone;
    self.player.view.frame = self.view.frame;
    [self.view addSubview:self.player.view];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(movieFinishedCallback:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:self.player];
    
    [self.player play]; //開始播放
- (void) movieFinishedCallback:(NSNotification*) aNotification {
    MPMoviePlayerController *player = [aNotification object];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];
    [player stop];
}

 

方法二:

1、要使用MPMoviePlayerViewController首先要加入MediaPlayer.framework. 
2、加入如下代碼:

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *url = [[NSBundle mainBundle] pathForResource:@"TaylorSwift-LoveStory" ofType:@"mp4"];
    
    MPMoviePlayerViewController *playerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieFinishedCallback:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:[playerViewController moviePlayer]];
    //-- add to view---
    [self.view addSubview:playerViewController.view];
    
    //---play movie---
    MPMoviePlayerController *player = [playerViewController moviePlayer];
    [player play];
    
}

- (void) movieFinishedCallback:(NSNotification*) aNotification {
    MPMoviePlayerController *player = [aNotification object];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];
    [player stop];
    [self.view removeFromSuperView];
    [player autorelease];
}

3、支持橫屏修改shouldAutorotateToInterfaceOrientation:interfaceOrientation方法使其返回YES。

備注:實測 用上面的方法直接播放本地m3u8格式或者線上的視頻也是可以的。

 

NSURL可直接初始化:

NSURL*videoPathURL=[NSURL URLWithString:urlStr];//urlStr是視頻播放地址

如果是播放本地視頻的話。這樣初始化:

NSURL*videoPathURL=[[NSURL alloc] initFileURLWithPath:urlStr];

 

轉:http://re-reference.iteye.com/blog/1106324


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM