iOS Question control phone ear speaker

bitmap1374

Member
Licensed User
hi

I want if the phone is placed on the ear. The sound is played through the phone ear speaker

What is the solution?

Thanks for your answers
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Based on: https://stackoverflow.com/questions/31692577/how-to-play-audio-through-built-in-earpiece-speaker

Works nicely.

B4X:
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private VideoPlayer1 As VideoPlayer
End Sub

Public Sub Initialize
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
    Me.As(NativeObject).RunMethod("addProximityMonitor", Null)
    VideoPlayer1.LoadVideoUrl("https://stream-dc1.radioparadise.com/mp3-32")
    VideoPlayer1.Play
End Sub

#if OBJC
- (void)addProximityMonitor {
    AVAudioSession* 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];
    }
    [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);
    AVAudioSession* audioSession = [AVAudioSession sharedInstance];
    if(device.proximityState == 0){
        [audioSession  overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
    }
    else{
        [audioSession  overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
    }
}
#End If
 
Upvote 0
Top