サウンド再生の環境作り
iPhone OS 2.2 以降のみを対象とする場合、AVAudioPlayer クラスを使うのが簡単である。再生、中断、再開、ボリュームの調整、再生時間の取得、再生位置の指定、delegate による再生状況の受け取りなど、一通りのことができる。
それ以上の機能が欲しい場合(左右のバランス調整など)や、iPhone OS 2.1 以前の環境への対応が求められる場合には、Apple の配布しているサンプルコードから、サウンド再生部分のソースコードを参照することになるだろう。WWDC 2008 の参加者にはゲーム向けのより詳細なサンプルコードが配布されているが、参加していない人も多く、基本的には、SpeakHere というサンプルを参照することになると思われる。また、がんばれば同じレベルのものに改良することは可能である。
SpeakHere のサンプルコードからは、
- AudioQueueObject.h
- AudioQueueObject.m
- AudioPlayer.h
- AudioPlayer.m
- MyOpenALSupport.h
を取り出す。
SpeakHere の AudioPlayer と圧縮音源
SpeakHere の AudioPlayer クラスには、圧縮音源を再生するために必要な処理が含まれていない。そのため、AAC や MP3 を再生する場合には、こちら の「Oct 11, 2008 3:12 AM」に投稿された内容に従って、数行のコードを追加してやる必要がある。
具体的には、AudioPlayer.m の - (void)setupAudioQueueBuffers メソッドの実装を、
- (void)setupAudioQueueBuffers
{
[self calculateSizesFor:(Float64)kSecondsPerBuffer];
for (int bufferIndex = 0; bufferIndex < kNumberAudioDataBuffers; bufferIndex++) {
AudioQueueAllocateBuffer([self queueObject], [self bufferByteSize], &buffers[bufferIndex]);
BOOL isFormatVBR = (audioFormat.mBytesPerPacket == 0 || audioFormat.mFramesPerPacket == 0);
if (isFormatVBR) {
packetDescriptions = (AudioStreamPacketDescription *)malloc(numPacketsToRead * sizeof(AudioStreamPacketDescription));
} else {
packetDescriptions = NULL;
}
playbackCallback(self, [self queueObject], buffers[bufferIndex]);
if ([self donePlayingFile]) {
break;
}
}
}
とする。
サウンド再生環境の初期化
サウンド再生に先駆けて、サウンド環境を再生用に初期化してやる必要がある。
UIApplication の delegate に、
void audioInterruptionListenerCallback(void *inUserData, UInt32 interruptionState)
{
}
このようなコールバックを用意しておき、applicationDidFinishLaunching: のタイミングで、
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
AudioSessionInitialize(NULL, NULL, interruptionListenerCallback, self);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
AudioSessionSetActive(true);
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
として初期化を行う。
あとは AudioPlayer を alloc して、URL で init して、play すればオッケーだ。
シミュレータとサウンド再生
2.2 用の環境では、サウンド再生を行うアプリケーションをシミュレータで実行すると、
2008-12-14 14:48:52.681 AudioTest[37296:20b] Error loading /Library/QuickTime/DivX Decoder.component/Contents/MacOS/DivX Decoder: dlopen(/Library/QuickTime/DivX Decoder.component/Contents/MacOS/DivX Decoder, 262): Symbol not found: _SCDynamicStoreCopyConsoleUser
というようなエラーが出る場合がある。「DivX Decoder.component」の部分は、環境によっていろんな「○○.component」に変わる。この場合、再生できるようになるまで「○○.component」を /Library/QuickTime から取り除いていけば、再生できるようになる。
コメントを書く