天天看點

Play video Files(播放視訊)

1。實作:

   導入: #import <MediaPlayer/MediaPlayer.h>

   MPMoviePlayerController:可進行更加全面的視訊顯示設定,它沒使用delegate,而是靠notification system

   MPMoviePlayerViewController:可以放入navigationController,簡單實作全屏顯示,

                               或是用presentMoviePlayerViewControllerAnimated進行模式視窗全屏顯示

e.g.

#import <MediaPlayer/MediaPlayer.h>

#import <AVFoundation/AVFoundation.h>    

@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

繼續閱讀