iPhoneで音を鳴らすには少なくとも2つ方法があります(3つあった気もするけどあと1つ忘れた)。
1つはSystemSoundIDを使う方法、もう1つはAudio Queue Servicesを使う方法です。
それぞれに特性や使い方が違うので、1つずつ見て行きましょう。
SystemSoundIDの特徴と使い方
○特徴
- 設置が比較的カンタン
- 30秒以内の音しか鳴らせない
- 音をループさせることはできない
- ネットワーク通信を行うアプリで使用すると、音量がiPhone本体の左ボタンで調節できなくなる
○使い方
// ヘッダーファイル @interface hogeViewController { SystemSoundID soundID; } - (IBAction)sounds01; // 実装ファイル @implementation hogeViewController - (IBAction)sounds01 { NSString *path = [[NSBundle mainBundle]pathForResource:@"1" ofType:@"caf"]; NSURL *url = [NSURL fileURLWithPath:path]; AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID); //サウンドを鳴らす AudioServicesPlaySystemSound(soundID); } // あとはInterface builderでボタンなどに対してsounds01をActionとしてひもづける // 必要なフレームワークはAudioToolbox.framework
○コメント
とってもシンプルなSystemSoundIDですが、いろいろと制約があるので使いにくい場面があるかもしれません。
そんなときは次のAudio Queue Servicesを使いましょう。
Audio Queue Servicesの特徴と使い方
○特徴
- 30秒以上の音でも鳴らせる
- 音のループが可能
- SystemSoundIDよりちょっぴり重たいかも?
○使い方
// ヘッダーファイル @interface hogeViewController { AVAudioPlayer *player; } @property (nonatomic, retain) AVAudioPlayer *player; - (IBAction)sounds01; // 実装ファイル @implementation hogeViewController @synthesize player; - (IBAction)sounds01 { NSString *path; NSURL *url; path = [[NSBundle mainBundle] pathForResource:@"0_1" ofType:@"caf"]; url = [NSURL fileURLWithPath:path]; self.newPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; // ここでループの回数を指定する。無限の場合はマイナスの数値を指定。 self.newPlay.numberOfLoops = 0; self.player = self.newPlay; //サウンドを鳴らす [self.player play]; } // 必要なフレームワークはAVFoundation.framework
○コメント
ループの回数等も指定できるので、通常はSystemSoundIDではなくこちらを使うべきだと思います。
SystemSoundIDだとAdmob広告などを表示させるだけで、ネットワーク通信を使うので音量調節ができなくなりますしね。
コメント