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

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

我正在使用这种方法:

[[UIDevice currentDevice] setProximityMonitoringEnabled:NO]; NSLog(@"%d",enable); UInt32 route; route = enable ? kAudioSessionOverrideAudioRoute_Speaker : kAudioSessionOverrideAudioRoute_None; AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(route), &route); 

提前致谢。

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]; } 

扬声器Onn Off的Swift 4

 //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) }