Reputation: 4540
I have seen some apps like WhatsApp has a feature to play audio clips only through earpiece(phone call speaker) when the user brings up the device near to ear. Otherwise its playing via normal built-in speaker.
I am using MPMoviePlayer for playing audio clips.
I did go through lots of similar questions and answers on the internet, and all the answers say to set the AudioSession Category to PlayAndRecord. Thats it.
I did the same, but couldn't get the exact result that I want to get.
// Audio Player
self.audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
self.moviePlayer = [[MPMoviePlayerController alloc] init];
self.moviePlayer.view.hidden = YES;
// AVAudioSessionPortDescription *routePort = self.audioSession.currentRoute.outputs.firstObject;
// NSString *portType = routePort.portType;
//
// if ([portType isEqualToString:@"Receiver"]) {
// [self.audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
// } else {
// [self.audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
// }
Can anyone please show me how and where can I modify the source to play audio through the earpiece speaker only when the user brings up the device?
Upvotes: 3
Views: 3479
Reputation: 4540
I could do it using AVAudioSession and ProximityMonitering
- (void)viewDidLoad {
[super viewDidLoad];
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
if ([UIDevice currentDevice].proximityMonitoringEnabled == YES) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(proximityChanged:)
name:@"UIDeviceProximityStateDidChangeNotification"
object:[UIDevice currentDevice]];
}
}
- (void) proximityChanged:(NSNotification *)notification {
UIDevice *device = [notification object];
NSLog(@"In proximity: %i", device.proximityState);
if(device.proximityState == 0){
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
}
else{
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
}
}
Play Audio
audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
AVAudioSessionPortDescription *routePort = audioSession.currentRoute.outputs.firstObject;
NSString *portType = routePort.portType;
NSLog(@"PortType %@", portType);
if ([portType isEqualToString:@"Receiver"]) {
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
}
Upvotes: 6