我有一个音频播放器,当接近传感器通知1时,可选择将音频输出从扬声器切换到接收器/听筒(无论是否连接了耳机).以下是我的代码.
- (void) switchAudioOutput:(Nsstring*)output{ AVAudioSession* audioSession = [AVAudioSession sharedInstance]; BOOL success; NSError* error; if([output isEqualToString:keAudioOutputReciever]){ //Force current audio out through reciever //set the audioSession override success = [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error]; if (!success) NSLog(@"AVAudioSession error overrideOutputAudioPort:%@",error); //activate the audio session success = [audioSession setActive:YES error:&error]; if (!success) NSLog(@"AVAudioSession error activating: %@",error); else NSLog(@"AVAudioSession active with override: AVAudioSessionPortOverrideNone"); }else if([output isEqualToString:keAudioOutputSpeaker]){ //set the audioSession override success = [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error]; if (!success) NSLog(@"AVAudioSession error overrideOutputAudioPort:%@",error); else NSLog(@"AVAudioSession active with override: AVAudioSessionPortOverrideSpeaker"); } }
这是基于答案Toggle Button route audio to speaker and receiver和enter link description here.我注意到这只会强制音频到扬声器,但不能确保路由单独进入接收器.此外,当转移到扬声器时,我收到以下错误:
AVAudioSession error overrideOutputAudioPort:Error Domain=NSOsstatusErrorDomain Code=-50 “The operation Couldn’t be completed. (Osstatus error -50.)”
解决方法
我通过避免覆盖Receiver来找出答案
- (void) setAudioSession:(Nsstring*)audioOutput{ NSError* error; if([audioOutput isEqualToString:audioOutputSpeaker.lowercaseString]){ //set the audioSession override if(![self setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionAllowBluetooth error:&error]) NSLog(@"AVAudioSession error AVAudioSessionCategoryPlayAndRecord:%@",error); //activate the audio session if (![self setActive:YES error:&error]) NSLog(@"AVAudioSession error activating: %@",error); else NSLog(@"AVAudioSession active with override: AVAudioSessionPortOverrideNone"); }else if ([audioOutput isEqualToString:audioOutputReciever.lowercaseString]){ //Force current audio out through reciever //set the audioSession override if(![self setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:&error]) NSLog(@"AVAudioSession error AVAudioSessionCategoryPlayAndRecord:%@",error); if (![self overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error]) NSLog(@"AVAudioSession error overrideOutputAudioPort to Reciever:%@",error); else NSLog(@"AVAudioSession active with override: AVAudioSessionPortOverrideNone"); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。