I am developing an application in which I want to redirect audio output to phone speaker, but I don't have idea how to do this programmatically.
Any idea about it?
I am developing an application in which I want to redirect audio output to phone speaker, but I don't have idea how to do this programmatically.
Any idea about it?
You cannot turn ON/OFF speakers through your app. However, you can sense the mute switch of your device. By that you can know the current status of speaker. This Question will lead you towards the solution.
For sake of completeness, let me paste the answer here..
// "Ambient" makes it respect the mute switch
// Must call this once to init session
if (!gAudioSessionInited)
{
AudioSessionInterruptionListener inInterruptionListener = NULL;
OSStatus error;
if ((error = AudioSessionInitialize (NULL, NULL, inInterruptionListener, NULL)))
{
NSLog(@"*** Error *** error in AudioSessionInitialize: %d.", error);
}
else
{
gAudioSessionInited = YES;
}
}
SInt32 ambient = kAudioSessionCategory_AmbientSound;
if (AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (ambient), &ambient))
{
NSLog(@"*** Error *** could not set Session property to ambient.");
}
Update: You need to override AudioRoute to turn on speakers when headset is plugged in. Use following code for the same.
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
Be sure to include the AudioToolbox lib in Xcode. I think it will solve your issue..
Let me know if more info needed..:)
-(IBAction)playAUdio
{
if(ishandset)
{
AVAudioSession* session = [AVAudioSession sharedInstance];
BOOL success;
NSError* error;
success = [session setCategory:AVAudioSessionCategoryPlayAndRecord
error:&error];
success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
error:&error];
success = [session setActive:YES error:&error];
}
else
{
UInt32 audioRouteOverride = kAudioSessionOutputRoute_Headphones;
AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
}
ishandset=!ishandset;
}