首页 > 代码库 > 使用MediaPlayer播放视频

使用MediaPlayer播放视频

使用MediaPlayer播放视频

by 伍雪颖

- (IBAction)userPlayerController:(id)sender {
    if (_moviePlayer == nil) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished4MoviePlayerController:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doneButtonClick:) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
        
        _moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[self movieURL]];
        
        _moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
        _moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
        
        [self.view addSubview:_moviePlayer.view];
    }
    [_moviePlayer play];
    [_moviePlayer setFullscreen:YES animated:YES];
}

- (void)playbackFinished4MoviePlayerController:(NSNotification *)notification {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_moviePlayer stop];
    [_moviePlayer.view removeFromSuperview];
    _moviePlayer = nil;
}

- (void)doneButtonClick:(NSNotification *)aNotification {
    if (_moviePlayer.playbackState == MPMoviePlaybackStateStopped) {
        [_moviePlayer.view removeFromSuperview];
        _moviePlayer = nil;
    }
}

- (IBAction)userPlayerViewController:(id)sender {
    if (_moviePlayerView == nil) {
        _moviePlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[self movieURL]];
        _moviePlayerView.moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
        _moviePlayerView.moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished4MoviePlayerViewController:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    }
    [self presentMoviePlayerViewControllerAnimated:_moviePlayerView];
}

- (void)playbackFinished4MoviePlayerViewController:(NSNotification *)notification {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_moviePlayerView dismissMoviePlayerViewControllerAnimated];
    _moviePlayerView = nil;
}

- (NSURL *)movieURL {
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *moviePath = [bundle pathForResource:@"xx" ofType:@"mp4"];
    if (moviePath) {
        return [NSURL fileURLWithPath:moviePath];
    }else {
        return nil;
    }
}


使用MediaPlayer播放视频