在呼叫时启用和禁用Xcode ios 8.1中的扬声器

时间:2014-12-02 09:59:14

标签: ios iphone xcode audio

我需要在从app调用时启用扬声器。我可以成功启用它,但我无法禁用它。

我正在使用这种方法:

[[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
NSLog(@"%d",enable);

UInt32 route;
route = enable ? kAudioSessionOverrideAudioRoute_Speaker :
kAudioSessionOverrideAudioRoute_None;

AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                         sizeof(route), &route);

提前致谢。

2 个答案:

答案 0 :(得分:14)

AudioSessionSetProperty已弃用。 https://developer.apple.com/library/ios/documentation/audiotoolbox/reference/audiosessionservicesreference/index.html#//apple_ref/c/func/AudioSessionSetProperty

- (void)setAudioOutputSpeaker:(BOOL)enabled
{
    AVAudioSession *session =   [AVAudioSession sharedInstance];
    NSError *error;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    [session setMode:AVAudioSessionModeVoiceChat error:&error];
    if (enabled) // Enable speaker
    {
        [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
    }
    else // Disable speaker
    {
        [session overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error];
    }
    [session setActive:YES error:&error];
}

答案 1 :(得分:1)

Swift 4 for Speaker Onn Off

//MARK:- Usage  for Enable
self.setAudioOutputSpeaker(enabled: true)

//MARK:- Usage  for Disable
self.setAudioOutputSpeaker(enabled: false)

//MARK:- Manual Speaker Enagle and Disable
func setAudioOutputSpeaker(enabled: Bool)
{
    let session = AVAudioSession.sharedInstance()
    var _: Error?
    try? session.setCategory(AVAudioSessionCategoryPlayAndRecord)
    try? session.setMode(AVAudioSessionModeVoiceChat)
    if enabled {
        try? session.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
    } else {
        try? session.overrideOutputAudioPort(AVAudioSessionPortOverride.none)
    }
    try? session.setActive(true)
}