1

我正在尝试检测用户是否按下耳机键,因为我正在使用 2 种方法。

-(void)headsetMicrophoneDetection
{
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [[MPRemoteCommandCenter sharedCommandCenter].togglePlayPauseCommand addTarget:self action:@selector(onTooglePlayPause)];

    NSLog(@"calling headset method");
}
-(void)onTooglePlayPause
{
    NSLog(@"kishore");
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)theEvent
{
    NSLog(@"callig method to :)");
    if (theEvent.type == UIEventTypeRemoteControl) {
        switch(theEvent.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                NSLog(@"Hello");
                break;
            case UIEventSubtypeRemoteControlPlay:
                NSLog(@"Hello 2");
                break;
            case UIEventSubtypeRemoteControlPause:
                NSLog(@"Hello 3");
                break;
            case UIEventSubtypeRemoteControlStop:
                NSLog(@"Hello 4");
                break;
            default:
                return;
        }
    }
}

但是在调用此方法后,我没有得到,我的代码有什么问题,我启用了后台服务以进行音频检查,并且我在 NSObject 类中使用了所有方法。

4

2 回答 2

0

请检查以下代码。

- (BOOL)isHeadsetPluggedIn {
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs]) {
        if ([[desc portType]     isEqualToString:AVAudioSessionPortHeadphones])
           return YES;
    }
    return NO;}
于 2016-07-22T08:43:48.450 回答
0

尝试将其包含在viewDidAppear

[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

而这在viewDidDisappear

[[AVAudioSession sharedInstance] setActive:NO error:nil];
于 2019-04-09T12:42:20.977 回答