开发者

Checking earphones connected to device programmatically?

开发者 https://www.devze.com 2022-12-11 06:41 出处:网络
I am using the AVAudioPlayer class to play .mp3 files in my App. Is it possible to check whether the earphones are connected to the device programmatically?

I am using the AVAudioPlayer class to play .mp3 files in my App. Is it possible to check whether the earphones are connected to the device programmatically?

In first generation iPod devices, the volume control bar is hidden (for music a开发者_JAVA技巧nd videos) when no earphones are connected.


You can get the current audio 'route' by calling AudioSessionGetProperty with the kAudioSessionProperty_AudioRoute property. This gives you a string such as "Headphone" or "Speaker".

You can also use AudioSessionAddPropertyListener to listen for when the route changes (eg. disconnecting headphones)

See the apple docs here


AudioSessionGetProperty and AudioSessionAddPropertyListener are deprecated in iOS 7.

Instead, use: AVAudioSessionRouteChangeNotification

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:nil];

Listener,

-(void)handleRouteChange:(NSNotification*)notification 
{
    NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    switch (reason) {
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable :
            break;
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable :
            break;
        case AVAudioSessionRouteChangeReasonOverride :
            break;
        case AVAudioSessionRouteChangeReasonCategoryChange :
            break;
        case AVAudioSessionRouteChangeReasonWakeFromSleep :
            break;
        case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory :
            break;
        case AVAudioSessionRouteChangeReasonRouteConfigurationChange :
            break;
        case AVAudioSessionRouteChangeReasonUnknown:
        default:
            break;
    }
}


There are two approaches:

1) check the instantaneous state of the audio route

Detect if headphones (not microphone) are plugged in to an iOS device

This answer furnishes you with a ready-made method for detecting whether headphones are plugged in.

2) monitor route change events, and set a flag whenever the route changes between headset and non-headset

How to programmatically detect earpiece in iphone?

( would probably want to add the code from the first link into this to actually determine whether headset/non-headset status has been changed within the route change callback )

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号