▼iPhoneプログラミングメモ▼
ムービーの再生

ムービーを再生するプログラムを作成する。


フレームワークの準備
MediaPlayer.frameworkを追加。

リソースの準備
以下のムービーをプロジェクトのResourcesにドラッグ&ドロップで追加。
動画の変換にはHandBrakeが便利。
sample.m4v

ソースコードの記述
MovieEx.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>

//MovieExの宣言
@interface MovieEx : UIViewController {
    MPMoviePlayerController* _player;
}
@end

MovieEx.m
#import "MovieEx.h"

//MovieExの実装
@implementation MovieEx

//ムービープレーヤーの生成
- (MPMoviePlayerController*)makeMoviePlayer:(NSString*)res {
    //リソースのURLの生成
    NSString* path=[[NSBundle mainBundle] pathForResource:res ofType:@""];
    NSURL* url=[NSURL fileURLWithPath:path];
        
    //ムービープレイヤーの生成
    MPMoviePlayerController* player=[[[MPMoviePlayerController alloc] 
        initWithContentURL:url] autorelease];
    player.scalingMode =MPMovieScalingModeAspectFit;
    player.controlStyle=MPMovieControlStyleEmbedded;
    return player;
}

//初期化
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor blackColor]];
       
    //ムービープレイヤーの生成
    _player=[[self makeMoviePlayer:@"sample.m4v"] retain];
    [_player.view setFrame:CGRectMake(0,0,320,320)];
    [self.view addSubview:_player.view];

    //ムービー完了の通知
    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(moviePlayBackDidFinish:) 
        name:MPMoviePlayerPlaybackDidFinishNotification 
        object:_player];

    //ムービーの再生
    [_player play];

    //端末のボリューム操作
    MPVolumeView* volumeView=[[[MPVolumeView alloc] init] autorelease]; 
    [volumeView setFrame:CGRectMake(0,420,320,40)];
	[self.view addSubview:volumeView];
}

//メモリ解放
- (void)dealloc {
    [_player release];
    [super dealloc];
}

//ムービー完了時に呼ばれる
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
    //ムービー完了原因の取得
    NSDictionary* userInfo=[notification userInfo];
    int reason=[[userInfo objectForKey:
        @"MPMoviePlayerPlaybackDidFinishReasonUserInfoKey"] intValue];
    if (reason==MPMovieFinishReasonPlaybackEnded) {
        NSLog(@"再生終了");
    } else if (reason==MPMovieFinishReasonPlaybackError) {
        NSLog(@"エラー");
    } else if (reason==MPMovieFinishReasonUserExited) {
        NSLog(@"フルスクリーン用UIのDoneボタンで終了");
    }
}

//画面を端末の向きにあわせて回転
- (BOOL)shouldAutorotateToInterfaceOrientation:
    (UIInterfaceOrientation)orientation {
    return YES;
}
@end



−戻る−