您的位置:首页 > 移动开发 > IOS开发

iOS之AudioSession详解

2014-09-03 10:23 190 查看
在你读这篇文章之前,如果你不嫌读英文太累,推荐阅读下苹果iOS Human Interface Guidelines中Sound这一章。

选择一个Category

AVAudioSessionCategoryAmbient
kAudioSessionCategory_AmbientSound


——用于非以语音为主的应用,使用这个category的应用会随着静音键和屏幕关闭而静音。并且不会中止其它应用播放声音,可以和其它自带应用如iPod,safari等同时播放声音。注意:该Category无法在后台播放声音

AVAudioSessionCategorySoloAmbient
kAudioSessionCategory_SoloAmbientSound


——类似于AVAudioSessionCategoryAmbient 不同之处在于它会中止其它应用播放声音。 这个category为默认category。该Category无法在后台播放声音

AVAudioSessionCategoryPlayback
kAudioSessionCategory_MediaPlayback


——用于以语音为主的应用,使用这个category的应用不会随着静音键和屏幕关闭而静音。可在后台播放声音

AVAudioSessionCategoryRecord
kAudioSessionCategory_RecordAudio


———
用于需要录音的应用,设置该category后,除了来电铃声,闹钟或日历提醒之外的其它系统声音都不会被播放。该Category只提供单纯录音功能。

AVAudioSessionCategoryPlayAndRecord
kAudioSessionCategory_PlayAndRecord


——用于既需要播放声音又需要录音的应用,语音聊天应用(如微信)应该使用这个category。该Category提供录音和播放功能。如果你的应用需要用到iPhone上的听筒,该category是你唯一的选择,在该Category下声音的默认出口为听筒(在没有外接设备的情况下)。

注意:并不是一个应用只能使用一个category,程序应该根据实际需要来切换设置不同的category,举个例子,录音的时候,需要设置为AVAudioSessionCategoryRecord,当录音结束时,应根据程序需要更改category为AVAudioSessionCategoryAmbient,AVAudioSessionCategorySoloAmbient或AVAudioSessionCategoryPlayback中的一种。

设置Category

[objc] view
plaincopy





NSError *setCategoryError = nil;

BOOL success = [[AVAudioSession sharedInstance]

setCategory: AVAudioSessionCategoryAmbient

error: &setCategoryError];

if (!success) { /* handle the error in setCategoryError */ }

Activate & Deactivate AudioSession

[objc] view
plaincopy





NSError *error = nil;

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

BOOL ret = [audioSession setActive:YES error:&error];

if (!ret)

{

NSLog(@"%s - activate audio session failed with error %@", __func__,[error description]);

}

[objc] view
plaincopy





NSError *error = nil;

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

//Note: Set AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation to resume other apps' audio.

BOOL ret = [audioSession setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];

if (!ret)

{

}

Audio Route的选择

当你的iPhone接有多个外接音频设备时(耳塞,蓝牙耳机等),AudioSession将遵循last-in wins的原则来选择外接设备,即声音将被导向最后接入的设备。

当没有接入任何音频设备时,一般情况下声音会默认从扬声器出来,但有一个例外的情况:在
PlayAndRecord
这个category下,听筒会成为默认的输出设备。如果你想要改变这个行为,可以提供MPVolumeView来让用户切换到扬声器,也可通过overrideOutputAudioPort方法来programmingly切换到扬声器,也可以修改category
option为AVAudioSessionCategoryOptionDefaultToSpeaker。

PlayandRecord下切换到扬声器

除了让用户手动选择,你也可以通过以下两种方法在程序里进行切换

1. 修改Category的默认行为:

[objc] view
plaincopy





[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:&error];

2. OverrideOutputAudioPort:

[objc] view
plaincopy





[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];

关于这两种方法的区别这篇文章中有详细的说明。

本文转载自:http://blog.csdn.net/xy5811/article/details/8563137
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: