我在用扬声器和麦克风切换音频时遇到问题。首先,当应用程序启动音频播放到默认扬声器时。然后按下按钮事件,我切换到麦克风,它在麦克风中播放。
但当我试着切换回扬声器时,它的麦克风播放对我来说不起作用。
代码
- (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];
}
请告诉我什么时候我做了错误的
我已经完成了以下代码
- (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];
}