How to play sound through the built-in speaker

I've seen some apps like WhatsApp have the feature to play sound clips only through the speaker (speaker of phone calls) when the user picks up the device near their ear. Otherwise, it is played back through the usual built-in speaker.

I am using MPMoviePlayer to play audio clips.

I have looked through many similar questions and answers on the internet and all the answers say to set the AudioSession category in PlayAndRecord. This is it.

I did the same but couldn't get the exact result 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 show me how and where I can change the source to play audio through the speaker only when the user calls the device?

+3


source to share


1 answer


I could do it with 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];
}

      

+5


source







All Articles