Mov形式のファイルもiPhoneでサポートされています。
ユーザー制御の動作とズームモード
通知の生成
MediaPlayer.frameworkの追加
MoviePlayerViewController.h
#import <MediaPlayer/MediaPlayer.h>
@interface MoviePlayerViewController : UIViewController {
MPMoviePlayerViewController * moviePlayerView;
}
@property (nonatomic, retain) MPMoviePlayerViewController * moviePlayerView;
-(IBAction) playMovie: (id) sender;
- (void) playingDone;
@end
mファイルのロードおよびアンロード方法
- (void) viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(playingDone) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[moviePlayerView release];
[super dealloc];
}
MPMoviePlayerViewController は、再生中の状態変化やその他のイベントに対する通知を提供します。再生完了通知はviewDidLoadに登録されます:
MPMoviePlayerPlaybackDidFinishNotificationは、再生終了を受信者に通知します。
MPMoviePlayerScalingModeDidChangeNotificationは、ムービーのサイズを変更します。
deallocメソッドの[[NSNotificationCenter defaultCenter]
removeObserver:self];映画が終了したらログオフする通知。
再生イベント
- (IBAction) playMovie: (id) sender {
moviePlayerView = [[MPMoviePlayerViewController alloc]
initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"short" ofType:@"3gp"]]];
moviePlayerView.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
moviePlayerView.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
// MPMovieControlStyleNone
//MPMovieControlStyleEmbedded
//MPMovieControlStyleDefault
//[movieplayer play];
//現在のビューにビューを追加する
[[[UIApplication sharedApplication] keyWindow] addSubview:moviePlayerView.view];
}
moviePlayerView.moviePlayerプロパティはMPMoviePlayerController型で、controlStyleプロパティを持っています。
再生動作の制御が可能で、以下の値を取ります:
MPMovieControlStyleFullscreen
MPMovieControlStyleNone には再生コントロールがありません。
MPMovieControlStyleEmbedded
MPMovieControlStyleDefault
MPMovieScalingModeAspectFit 塗りつぶし方向へのスケーリング。
MPMovieScalingModeAspectFill 両側が部分的に切り取られることがあります。
MPMovieScalingModeFill 両側を塗りつぶすとスケールが変わることがあります。
再生完了
- (void) playingDone {
NSLog(@"再生完了");
[moviePlayerView.view removeFromSuperview];
[moviePlayerView release];
moviePlayerView = nil;
}
playDoneメソッドは、Notification Centreに登録されたメソッドにより、ムービーの再生が終了したときに呼び出されます。
再生が終了したら、再生ビューを削除し、前の画面を取得できるようにする必要があります。
オーディオ再生
12.2.1 オーディオファイル入門
オーディオファイル形式には大きく分けて2種類あります:
WAV、PCM、TTA、FLAC、AU、APE、TAK、WavPack(WV)、CAFなどのロスレスフォーマット
MP3、Windows Media Audio、Ogg Vorbis、AACなどのロッシーフォーマット
オーディオファイルの移動
モバイル機器としてのオーディオファイルは、原則的に比較的小さく、一般的なフォーマットであるべきです:
WAV、最高のロスレス圧縮のため。
MP3は非可逆圧縮で、ファイルサイズが小さく、人間が感じ取れない音を取り除くのでうまく機能します。これは現在一般的に使われているフォーマットです。
AAC、圧縮率が高く、MP3ファイルよりも小さい。
CAFはアップル向けの可逆圧縮フォーマットです。
12.2.2 コアオーディオ
高度なAPI、使いやすい
System Sound API - 短いサウンド、警告音などを再生します。
AVFoundationは長時間のサウンド再生が可能です。
オーディオをよりコントロールできる低レベルAPI
Audio Toolbox - 録音、再生、オーディオストリーミングをフルコントロール。
OpenAL - ステレオサウンドを再生します。
12.2.3 システムサウンドAPI
システム・サウンドは、5秒以内の "短い "音を再生することができます。 ループなし、サウンドコントロールなし、即時再生。
再生フォーマットの制限:
リニアPCMとIMA4
.caf .aif または .wav
ショートサウンド
短い音」を演奏するには、2つのステップがあります:
声の登録
AudioServicesCreateSystemSoundID ((CFURLRef)fileURL, &myID);
サウンド再生
AudioServicesPlaySystemSound (myID);
完了イベントメソッドのリスニング
AudioServicesAddSystemSoundCompletion
クリアな再生音ID
SystemSoundID myID;
AudioServicesDisposeSystemSoundID (myID);
強く影響
また、System Sound APIを使ってiPhoneを振動させることも可能ですが、iPod touchはできません。
AudioServicesPlaySystemSound ;
#p#
実例
システムサウンドサービス
AudioToolbox.フレームワークの追加
SystemSoundServicesViewController.h ファイル
#import <UIKit/UIKit.h>
#include <AudioToolbox/AudioToolbox.h>
@interface SystemSoundServicesViewController : UIViewController;
- (IBAction) playSystemSound;
- (IBAction) vibrate;
@end
再生イベント
- (IBAction) playSystemSound{
NSURL* system_sound_url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"BeepGMC500" ofType:@"wav"]];
SystemSoundID system_sound_id;
AudioServicesCreateSystemSoundID(
(CFURLRef)system_sound_url,
&system_sound_id
);
// Register the sound completion callback.
AudioServicesAddSystemSoundCompletion(
system_sound_id,
NULL, // uses the main run loop
NULL, // uses kCFRunLoopDefaultMode
MySoundFinishedPlayingCallback, // the name of our custom callback function
NULL // for user data, but we don't need to do that in this case, so we just pass NULL
);
// Play the System Sound
AudioServicesPlaySystemSound(system_sound_id);
}
AudioServicesAddSystemSoundCompletionメソッド5つのパラメータは、最初のパラメータSystemSoundIDは、2番目のパラメータは、ループを使用するかどうかです3番目のパラメータは、ループモードは、4番目のパラメータは、コールバック関数は、再生が完了したときにコールバックメソッドは、5番目のパラメータは、コールバック関数のパラメータを提供することです。
ここでのコールバック・メソッドはCスタイルの関数、MySoundFinishedPlayingCallbackです。
コールバック関数
void MySoundFinishedPlayingCallback(SystemSoundID sound_id, void* user_data){
AudioServicesDisposeSystemSoundID(sound_id);
}
振動メソッド呼び出し
// Vibrate on action
- (IBAction) vibrate{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
音声の再生と録音
AVFoundationコントロールは、一般的なオーディオ再生と録音を可能にします。
AVAudioPlayerオーディオプレーヤークラスは、5秒以上のサウンドを再生するために使用され、ローカルのサウンドを再生することができますが、ネットワークメディアファイルを再生することはできません。再生、一時停止、ループ、スキップ操作ができます。
AVAudioRecorder 音声録音クラス。
インスタンス AVAudioPlayer
AVFoundation.フレームワークの追加
AvplayerViewController.hファイル
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface AvplayerViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer * player;
}
- (IBAction) stopSong: (id) sender;
- (IBAction) playSong: (id) sender;
@end
AvplayerViewController.m
#import "AvplayerViewController.h"
@implementation AvplayerViewController
- (IBAction) playSong: (id) sender {
NSError *error = nil;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"charleston1925_64kb" ofType:@"mp3"]] error:&error];
player.delegate = self;
if(error) {
NSLog(@"%@",[error description]);
[error release];
}
[player play];
}
- (IBAction) stopSong: (id) sender {
[player stop];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
NSLog(@"再生完了");
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
NSLog(@"再生エラーが発生した: %@", [error localizedDescription]);
}
- (void)dealloc {
[player release];
[super dealloc];
}
@end
AVAudioPlayer デリゲート
AVAudioPlayerDelegate デリゲートオブジェクトは二つの主要なメソッドを提供します:
audioPlayerDidFinishPlaying:成功しました。
audioPlayerDecodeErrorDidOccur:エラー。
AVAudioRecorder
新しい例:レコーダー
RecorderViewController.hファイル
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface RecorderViewController : UIViewController
{
AVAudioRecorder *recorder;
AVAudioPlayer *player;
UILabel *label;
}
@property (retain, nonatomic) AVAudioRecorder * recorder;
@property (retain, nonatomic) AVAudioPlayer * player;
@property (retain, nonatomic) IBOutlet UILabel *label;
-(IBAction)recordPushed:(id)sender;
-(IBAction)playPushed:(id)sender;
-(IBAction)stopPushed:(id)sender;
@end
オーディオ録音方法
-(IBAction)recordPushed:(id)sender
{
label.text = @"recode...";
if([recorder isRecording])
return;
if([player isPlaying])
[player stop];
NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord
error:&error];
[[AVAudioSession sharedInstance] setActive:YES error:&error];
AVAudioSessionはオーディオカテゴリを指定することで実装され、アプリケーションがオーディオを使用する方法を記述します。以下の文は、オーディオセッションクラスを設定します:
[[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryRecord error:&error];
AVAudioSessionCategoryRecordは、音声入力、つまり音声の録音しかできないことを意味します。他のオーディオ再生を停止する効果があります。
カテゴリーを使用した後、オーディオセッションを "Active "アクティブに設定してください。
[AVAudioSession sharedInstance] setActive:YES error:&error];
オーディオ録音方法
NSMutableDictionary *settings = [NSMutableDictionary dictionary];
[settings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM]
forKey:AVFormatIDKey];
[settings setValue:[NSNumber numberWithFloat:44100.0]
forKey:AVSampleRateKey]; //サンプルレート
[settings setValue:[NSNumber numberWithInt:1]
forKey:AVNumberOfChannelsKey];//チャンネル数
[settings setValue:[NSNumber numberWithInt:16]
forKey:AVLinearPCMBitDepthKey];//采样位数 默认 16
[settings setValue:[NSNumber numberWithBool:NO]
forKey:AVLinearPCMIsBigEndianKey];//大端还是小端 是内存的组织方式
[settings setValue:[NSNumber numberWithBool:NO]
forKey:AVLinearPCMIsFloatKey];//サンプリング信号が整数か浮動小数点数か
NSString *filePath =
[NSString stringWithFormat:@"%@/rec_audio.caf", [self documentsDirectory]];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
//[self setRecorder:nil];
recorder = [[AVAudioRecorder alloc]
initWithURL:fileUrl
settings:settings
error:&error];
// [recorder setMeteringEnabled:YES];
[recorder record];
}
-(NSString *)documentsDirectory{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); return [paths objectAtIndex:0]; }
オーディオ再生方式
-(IBAction)playPushed:(id)sender{
label.text = @"play...";
if([recorder isRecording])
[recorder stop];
if([player isPlaying])
[player stop];
NSString *filePath =
[NSString stringWithFormat:@"%@/rec_audio.caf", [self documentsDirectory]];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSError *error = nil;
// [self setPlayer:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
error:&error];
[[AVAudioSession sharedInstance] setActive:YES error:&error];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
// [player setMeteringEnabled:YES];
[player play];
}
オーディオ停止方式
-(IBAction)stopPushed:(id)sender{
label.text = @"stop...";
if([recorder isRecording])
[recorder stop];
if([player isPlaying])
[player stop];
}