ミュージックなどで音楽をかけながら使いたいアプリだったり、
同じ音を何度も鳴らしてかぶる場合に、重なって聞こえるようにする方法。
普通の方法だと音をかぶせると先に鳴らした音が消えるらしい。
appDelegateを使う。
MP3とかの音源だと出来なくて.cafという形式を使う。
ターミナルやitunesで変換できるらしいので変換して入れておく。
ストーリーボードでボタンを作成して接続しておく。
AVFoundationフレームワークを使うので入れる。
コードは
ViewController.h
#import <AVFoundation/AVFoundation.h> @interface ViewController : UIViewController <UIAlertViewDelegate, AVAudioPlayerDelegate> @property (strong) NSMutableArray *souldplayers;//音を鳴らすためのプロパティ @end
ViewController.m
#import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //音を鳴らすための配列を作成 self.souldplayers = [NSMutableArray arrayWithCapacity:0]; } #pragma mark - ringing //音を鳴らす - (IBAction)ringing:(UIButton *)sender { [self playHitSound]; } - (void)playHitSound { //アプリに組み込んだサウンドファイルのファイルパスを取得する NSString *soundPath; soundPath = [[NSBundle mainBundle] pathForResource:@"rin" ofType:@"caf"]; //URLにする NSURL *fileURL = [NSURL fileURLWithPath:soundPath]; //サウンドファイルを読み込む AVAudioPlayer *player; player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL]; //デリゲートを指定する [player setDelegate:self]; //配列に入れる [self.souldplayers addObject:player]; NSLog(@"souldplayers.count = %lu", (unsigned long)[self.souldplayers count]); //=> 0 [player play]; } //効果音の再生が完了した時の処理 - (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { //インスタンスを削除する [self.souldplayers removeObject:player]; }
appDlegate.mにAVfoundationをインポート
applicationDidBecomeActiveにコード追記
#import "AppDelegate.h" #import <AVFoundation/AVFoundation.h> @implementation AppDelegate - (void)applicationDidBecomeActive:(UIApplication *)application { AVAudioSession *session = [AVAudioSession sharedInstance]; [session setCategory:AVAudioSessionCategoryAmbient error:NULL]; [session setActive:YES error:NULL]; // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } @end
こんな感じで。
鳴るかな?
2016/04/20追記
参考サイト
【iOS】音楽を止めずに効果音を同時に再生するには|てくめも@ecoop.net
[iPhone] AVAudioplayer で音楽の再生 (Objective-C)
AVAudioPlayerを使用した曲の再生/停止/ボリューム調節サンプル – Dolice Lab
Objective-C:音楽(BGM)や効果音(SE)等のサウンド再生方法 | siro:chro