iOSオーディオとビデオ(Audio & Video)


概要

オーディオとビデオは最新のデバイスではかなり一般的です。

iosAVFoundation.frameworkとMediaPlayer.frameworkをXcodeプロジェクトに追加することで、iOSでオーディオとビデオ(Audio & Video)をサポートできます。

実装手順

1. シンプルなView based applicationを作成する

2. プロジェクトファイルを選択し、ターゲットを選択して、AVFoundation.frameworkとMediaPlayer.frameworkを追加する

3. ViewController.xibに2つのボタンを追加し、それぞれオーディオとビデオを再生するためのアクション(action)を作成する

4. ViewController.hを次のように更新する

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface ViewController : UIViewController
{
    AVAudioPlayer *audioPlayer;
    MPMoviePlayerViewController *moviePlayer;
    
}
-(IBAction)playAudio:(id)sender;
-(IBAction)playVideo:(id)sender;
@end

5. ViewController.mを次のように更新する

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
}
-(IBAction)playAudio:(id)sender{
   NSString *path = [[NSBundle mainBundle]
   pathForResource:@"audioTest" ofType:@"mp3"];
   audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:
   [NSURL fileURLWithPath:path] error:NULL];
   [audioPlayer play];
}
-(IBAction)playVideo:(id)sender{
   NSString *path = [[NSBundle mainBundle]pathForResource:
   @"videoTest" ofType:@"mov"];
   moviePlayer = [[MPMoviePlayerViewController 
   alloc]initWithContentURL:[NSURL fileURLWithPath:path]];
   [self presentModalViewController:moviePlayer animated:NO];
}
@end

注意事項

期待した出力を得るには、オーディオファイルとビデオファイルを追加する必要があります

出力

このプログラムを実行すると、次のような出力結果が得られます

AudioVideo_Output

「play video(ビデオを再生)」をクリックすると、次のように表示されます:

video_Output

その他の拡張