我在使用扬声器和麦克风切换音频时遇到问题。首先,app app启动音频播放到默认扬声器。然后在按钮事件上我改变了它在麦克风中播放的麦克风。
但是,当我试图切换回扬声器时,它不能为我播放麦克风。
代码
- (IBAction)setSpeakerPhoneEnabled:(UIButton *)sender
{
AVAudioSession* session = [AVAudioSession sharedInstance];
BOOL success;
NSError* error;
if (isHeadPhone) {
[session setCategory:AVAudioSessionCategoryPlayAndRecord
error:&error];
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
else{
success = [session setCategory:AVAudioSessionCategoryPlayback
error:&error];
UInt32 audioRouteOverride = kAudioSessionOutputRoute_Headphones;
AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
}
isHeadPhone = !isHeadPhone;
[self setTheSpekerImage];
}
当我做错时请告诉我
答案 0 :(得分:0)
我已完成以下代码
- (IBAction)setSpeakerPhoneEnabled:(UIButton *)sender
{
AudioSessionInitialize (NULL, NULL, NULL, NULL);
if (isHeadPhone) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,sizeof (audioRouteOverride),&audioRouteOverride);
[[AVAudioSession sharedInstance] setActive:YES error:nil];
}
else{
UInt32 dataSize = sizeof(CFStringRef);
CFStringRef currentRoute = NULL;
OSStatus result = noErr;
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &dataSize, ¤tRoute);
// Set the category to use the speakers and microphone.
UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
result = AudioSessionSetProperty (
kAudioSessionProperty_AudioCategory,
sizeof (sessionCategory),
&sessionCategory
);
assert(result == kAudioSessionNoError);
Float64 sampleRate = 44100.0;
dataSize = sizeof(sampleRate);
result = AudioSessionSetProperty (
kAudioSessionProperty_PreferredHardwareSampleRate,
dataSize,
&sampleRate
);
assert(result == kAudioSessionNoError);
// Default to speakerphone if a headset isn't plugged in.
// Overriding the output audio route
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
dataSize = sizeof(audioRouteOverride);
AudioSessionSetProperty(
kAudioSessionProperty_OverrideAudioRoute,
dataSize,
&audioRouteOverride);
assert(result == kAudioSessionNoError);
AudioSessionSetActive(YES);
//
}
isHeadPhone = !isHeadPhone;
[self setTheSpekerImage];
}