1

iPhoneに接続されたヘッドホンでユーザー入力(クリック)を検出しようとしています。これまでのところ、AVAudioSessionを使用して中断を検出する方法しか見つけていません。AVAudioSessionは正しいですか、それとも別の方法がありますか?どうやって?

4

2 に答える 2

1

あなたはこれを求めている:

beginReceivingRemoteControlEvents

VCクラスの1つにこれを実装します。

 // If using a nonmixable audio session category, as this app does, you must activate reception of 
//    remote-control events to allow reactivation of the audio session when running in the background.
//    Also, to receive remote-control events, the app must be eligible to become the first responder.
- (void) viewDidAppear: (BOOL) animated {

    [super viewDidAppear: animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

- (BOOL) canBecomeFirstResponder {

    return YES;
}


    // Respond to remote control events

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {

    if (receivedEvent.type == UIEventTypeRemoteControl) {

        switch (receivedEvent.subtype) {

            case UIEventSubtypeRemoteControlTogglePlayPause:
                [self playOrStop: nil];
                break;

            default:
                break;
        }
    }
}

こちらのサンプルコードをご覧ください

于 2011-10-25T20:23:15.343 に答える
1

iOS 7以降、さらに簡単になりました。ヘッドフォンの再生/一時停止ボタンが押されたときにブロックを実行するには、次の手順に従います。

    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];

    [commandCenter.togglePlayPauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"toggle button pressed");
        return MPRemoteCommandHandlerStatusSuccess;
    }];

または、ブロックの代わりにメソッドを使用する場合は、次のようにします。

    [commandCenter.togglePlayPauseCommand addTarget:self action:@selector(toggleButtonAction)];

止まる:

    [commandCenter.togglePlayPauseCommand removeTarget:self];

また:

    [commandCenter.togglePlayPauseCommand removeTarget:self action:@selector(toggleButtonAction)];

これをファイルのインクルード領域に追加する必要があります。

@import MediaPlayer;
于 2015-09-03T10:39:00.197 に答える