// // 监听音频打断事件
// setup our audio session
AVAudioSession *sessionInstance = [AVAudioSession sharedInstance];
// add interruption handler
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(audioSessionWasInterrupted:)
name:AVAudioSessionInterruptionNotification
object:sessionInstance];
NSError *error = nil;
[sessionInstance setCategory:AVAudioSessionCategoryPlayback error:&error];
if(nil != error) NSLog(@"Error setting audio session category! %@", error);
else {
[sessionInstance setActive:YES error:&error];
if (nil != error) NSLog(@"Error setting audio session active! %@", error);
}
- (void)audioSessionWasInterrupted:(NSNotification *)notification
{
NSLog(@"the notification is %@",notification);
if (AVAudioSessionInterruptionTypeBegan == [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue])
{
NSLog(@"begin");
}
else if (AVAudioSessionInterruptionTypeEnded == [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue])
{
NSLog(@"begin - end");
}
}
Apple Demo
https://developer.apple.com/library/prerelease/content/samplecode/MusicCube/Introduction/Intro.html
AVAudioSessionCategory说明
http://blog.sina.com.cn/s/blog_7ea0400d0102vjur.html
AVAudioSessionCategoryAmbient 或 kAudioSessionCategory_AmbientSound
用于非以语音为主的应用,使用这个category的应用会随着静音键和屏幕关闭而静音。并且不会中止其它应用播放声音,可以和其它自带应用如iPod,safari等同时播放声音。注意:该Category无法在后台播放声音
AVAudioSessionCategorySo loAmbient 或 kAudioSessionCategory_SoloAmbientSound
类似于AVAudioSessionCategoryAm bient 不同之处在于它会中止其它应用播放声音。 这个category为默认category。该Category无法在后台播放声音
AVAudioSessionCategoryPl ayback 或 kAudioSessionCategory_MediaPlayback
用于以语音为主的应用,使用这个category的应用不会随着静音键和屏幕关闭而静音。可在后台播放声音
AVAudioSessionCategoryRe cord 或 kAudioSessionCategory_RecordAudio
用于需要录音的应用,设置该category后,除了来电铃声,闹钟或日历提醒之外的其它系统声音都不会被播放。该Category只提供单纯录音功能。
AVAudioSessionCategoryPl ayAndRecord 或 kAudioSessionCategory_PlayAndRecord
用于既需要播放声音又需要录音的应用,语音聊天应用(如微信)应该使用这个category。该Category提供录音和播放功能。如果你的应用需要用到iPhone上的听筒,该category是你唯一的选择,在该Category下声音的默认出口为听筒(在没有外接设备的情况下)。
注意:并不是一个应用只能使用一个category,程序应该根据实际需要来切换设置不同的category,举个例子,录音的时候,需要设置为AVAudioSessionCategoryRe cord,当录音结束时,应根据程序需要更改category为AVAudioSessionCategoryAm bient,AVAudioSessionCategorySo loAmbient或AVAudioSessionCategoryPl ayback中的一种。