iOSオーディオ開発のためのAVAudioPlayerの使用、効果音再生のためのAudioServicesPlaySystemSoundの使用



Use Avaudioplayer



AVAudioPlayerを使用したオーディオ開発
AVAudioPlayerは、iOSシステムに付属のローカルmp3ファイルを再生できるクラスです(注:ローカル再生のみ)
参照: http://www.jianshu.com/p/589999e53461
1.最初にライブラリAVFoundation / AVFoundation.hとプロキシAVAudioPlayerDelegateをインポートします
2.再生するmp3ファイルをプロジェクトにインポートします
以下のコードを貼り付けます。
使用する必要のあるグローバル変数を定義します
@property(非アトミック、強力)AVAudioPlayer * player
@property(weak、nonatomic)IBOutlet UIProgressView * Progress
@property(weak、nonatomic)IBOutlet UILabel * CurrentTime
@property(weak、nonatomic)IBOutlet UILabel * countTime
@property(nonatomic、strong)NSArray * sourceArray // Song array
@property(nonatomic、copy)NSString * currentsong
@property(nonatomic、strong)NSTimer * timer // Timer

-(void)viewDidLoad {
[スーパーviewDidLoad]



_sourceArray = @[@'muise',@'music2'] NSUserDefaults *usedefault = [NSUserDefaults standardUserDefaults] NSString *songStr = [usedefault objectForKey:@'current_song'] if (songStr.length == 0) { songStr = _sourceArray[0] [usedefault setObject:@'0' forKey:@'current_song'] [usedefault synchronize] } NSString *str = _sourceArray[[songStr intValue]] [self PlayMusicWith:str] _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES] [_timer setFireDate:[NSDate distantFuture]] // Do any additional setup after loading the view, typically from a nib.

}

//一時停止ボタン
-(IBAction)Stop:(id)sender {



[self.player stop] [_timer setFireDate:[NSDate distantFuture]]

}

//次へボタン
-(IBAction)Next:(id)sender {

[self NextSong]

}



//前のボタン
-(IBAction)Previous:(id)sender {

NSUserDefaults *usedefault = [NSUserDefaults standardUserDefaults] NSString *songStr = [usedefault objectForKey:@'current_song'] int a = [songStr intValue]-1 if (a <0) { a = (int)_sourceArray.count -1 [usedefault setObject:[NSString stringWithFormat:@'%d',a] forKey:@'current_song'] [usedefault synchronize] }else{ [usedefault setObject:[NSString stringWithFormat:@'%d',a]forKey:@'current_song'] [usedefault synchronize] } NSLog(@'Previous songa==== %d',a) [self PlayMusicWith:_sourceArray[a]]

}

//プレーヤーを初期化して再生します
-(void)PlayMusicWith:(NSString *)songName {

NSURL *url = [[NSBundle mainBundle] URLForResource:songName withExtension:@'mp3'] self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil] self.player.delegate = self NSInteger countTime = self.player.duration _countTime.text = [NSString stringWithFormat:@'%d:%d',(int)countTime/60,(int)countTime%60]//Total length of the song [self.player play] //Set the lock screen to continue playing [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil] [[AVAudioSession sharedInstance] setActive: YES error: nil]

}

//プロキシメソッド

//再生後に自動的に次の曲に切り替えます
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)playersuccessfully:(BOOL)flag {
NSLog(@ '再生が終了しました')
//次の曲に切り替えます

[self NextSong]

}

//割り込み
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
NSLog(@ '通常、このメソッドはオーディオを一時停止します')
// [プレーヤーの停止]
}

//このメソッドは、割り込みが終了したときに呼び出されます
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags {
//通常、この方法でオーディオを再生し続けます
【プレイヤープレイ】
NSLog(@ '再生を続行')
}

//このメソッドは、デコードが間違っている場合に呼び出されます
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer )プレーヤーエラー:(NSError )エラー{
NSLog(@ 'ファイルエラー')
}

//次の曲
-(void)NextSong {

NSUserDefaults *usedefault = [NSUserDefaults standardUserDefaults] NSString *songStr = [usedefault objectForKey:@'current_song'] int a = [songStr intValue]+1 if (a >=_sourceArray.count) { a = 0 [usedefault setObject:@'0' forKey:@'current_song'] [usedefault synchronize] }else{ [usedefault setObject:[NSString stringWithFormat:@'%d',a]forKey:@'current_song'] [usedefault synchronize] } NSLog(@'Next songa==== %d',a) [self PlayMusicWith:_sourceArray[a]]

}

-(void)timerAction {

NSUInteger a = self.player.currentTime

// _CurrentTime.text = [[NSString stringWithFormat:@”%。2f”、a / 60.00、self.player.currentTime] stringByReplacingOccurrencesOfString:@”。” withString:@”:”]

NSLog(@'kkkk %ld %f',a,self.player.currentTime) int b = a%60 if (b<10) { } int c = (int)a/60 _CurrentTime.text =[NSString stringWithFormat:@'%d:%d',c,b]// [[NSString stringWithFormat:@'%',a/60.00] stringByReplacingOccurrencesOfString:@'.' withString:@':'] _Progress.progress = _player.currentTime/_player.duration

}

オーディオ再生AudioServicesPlaySystemSoundの使用
-(IBAction)Playmusic:(id)sender {

NSLog(@' Play') [self.player play] [_timer setFireDate:[NSDate distantPast]] NSLog(@'hhhh %f',self.player.currentTime)

}

-(void)playSoundEffect:(NSString *)name {

//Get the path of the file NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:name ofType:nil] NSURL *fileUrl = [NSURL fileURLWithPath:audioFilePath] //1. Get system sound ID SystemSoundID soundID = 0 AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID) //2. How to perform certain operations after playing, you can call the following method AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL,soundCompleteCallBack, NULL) //3. Play audio AudioServicesPlaySystemSound(soundID) // This method directly monitors the playback completion callback, which is a lot more convenient AudioServicesPlaySystemSoundWithCompletion(soundID, ^{ NSLog(@'Playback complete callback') }) AudioServicesPlayAlertSound(soundID) // Play and vibrate

}

void soundCompleteCallBack(SystemSoundID soundID、void * clientDate){

NSLog(@'Playing complete')

}
画像