如何以编程方式检测iPhone中的耳机?

时间:2009-12-02 10:32:35

标签: iphone ipod audio-player

我目前正在开展一个涉及在应用内部播放iphone音乐库音乐的项目。我正在使用MPMediaPickerController来允许用户选择他们的音乐并使用iPhone内的iPod音乐播放器播放。

然而,当用户插入耳机并将其移除时,我遇到了问题。音乐将无缘无故地突然停止播放。经过一些测试后,我发现当用户从设备上拔下耳机时,iPod播放器会暂停播放。那么有没有办法以编程方式检测耳机是否已拔下,以便我可以继续播放音乐?或者有什么方法可以防止iPod播放器在用户拔下耳机时暂停?

4 个答案:

答案 0 :(得分:9)

您应该注册AudioRoute更改通知并实现您希望如何处理路径更改

    // Registers the audio route change listener callback function
    AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange,
                                     audioRouteChangeListenerCallback,
                                     self);

并且在回调中,您可以获得路线更改的原因

  CFDictionaryRef   routeChangeDictionary = inPropertyValue;

  CFNumberRef routeChangeReasonRef =
  CFDictionaryGetValue (routeChangeDictionary,
            CFSTR (kAudioSession_AudioRouteChangeKey_Reason));

  SInt32 routeChangeReason;

      CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);

  if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) 
  {
       // Headset is unplugged..

  }
  if (routeChangeReason == kAudioSessionRouteChangeReason_NewDeviceAvailable)
  {
       // Headset is plugged in..                   
  }

答案 1 :(得分:4)

如果您只想检查是否在任何给定时间插入耳机,而无需听取路线更改,您只需执行以下操作:

OSStatus error = AudioSessionInitialize(NULL, NULL, NULL, NULL);
if (error) 
    NSLog("Error %d while initializing session", error);

UInt32 routeSize = sizeof (CFStringRef);
CFStringRef route;

error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
                                 &routeSize,
                                 &route);

if (error) 
    NSLog("Error %d while retrieving audio property", error);
else if (route == NULL) {
    NSLog(@"Silent switch is currently on");
} else  if([route isEqual:@"Headset"]) {
    NSLog(@"Using headphones");
} else {
    NSLog(@"Using %@", route);
}

干杯, Raffaello Colasante

答案 2 :(得分:2)

我发现您正在使用MPMediaPlayer Framework,但麦克风处理是使用AVAudioPlayer框架完成的,您需要将其添加到项目中。

Apple的网站上有来自AVAudioPlayer框架的代码,用于处理插入或移除Apple麦克风耳机的用户的中断。

查看Apple的iPhone Dev Center Audio Session Programming Guide

- (void) beginInterruption {
    if (playing) {
        playing = NO;
        interruptedWhilePlaying = YES;
        [self updateUserInterface];
    }
}

NSError *activationError = nil;
- (void) endInterruption {
    if (interruptedWhilePlaying) {
        [[AVAudioSession sharedInstance] setActive: YES error: &activationError];
        [player play];
        playing = YES;
        interruptedWhilePlaying = NO;
        [self updateUserInterface];
    }
}

我的代码有点不同,其中一些可能会对您有所帮助:

    void interruptionListenerCallback (
                                   void *inUserData,
                                   UInt32   interruptionState
) {
    // This callback, being outside the implementation block, needs a reference
    //  to the AudioViewController object
    RecordingListViewController *controller = (RecordingListViewController *) inUserData;

    if (interruptionState == kAudioSessionBeginInterruption) {

        //NSLog (@"Interrupted. Stopping playback or recording.");

        if (controller.audioRecorder) {
            // if currently recording, stop
            [controller recordOrStop: (id) controller];
        } else if (controller.audioPlayer) {
            // if currently playing, pause
            [controller pausePlayback];
            controller.interruptedOnPlayback = YES;
        }

    } else if ((interruptionState == kAudioSessionEndInterruption) && controller.interruptedOnPlayback) {
        // if the interruption was removed, and the app had been playing, resume playback
        [controller resumePlayback];
        controller.interruptedOnPlayback = NO;
    }
}

void recordingListViewMicrophoneListener (
                         void                      *inUserData,
                         AudioSessionPropertyID    inPropertyID,
                         UInt32                    inPropertyValueSize,
                         const void                *isMicConnected
                         ) {

    // ensure that this callback was invoked for a change to microphone connection
    if (inPropertyID != kAudioSessionProperty_AudioInputAvailable) {
        return;
    }

    RecordingListViewController *controller = (RecordingListViewController *) inUserData;

    // kAudioSessionProperty_AudioInputAvailable is a UInt32 (see Apple Audio Session Services Reference documentation)
    // to read isMicConnected, convert the const void pointer to a UInt32 pointer
    // then dereference the memory address contained in that pointer
    UInt32 connected = * (UInt32 *) isMicConnected;

    if (connected){
        [controller setMicrophoneConnected : YES];
    }
    else{
        [controller setMicrophoneConnected: NO];    
    }

    // check to see if microphone disconnected while recording
    // cancel the recording if it was
    if(controller.isRecording && !connected){
        [controller cancelDueToMicrophoneError];
    }
}

答案 3 :(得分:2)

嘿伙计们只需查看AddMusic示例应用。将解决所有与iPod相关的问题

首先使用以下代码注册iPod播放器以进行通知

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

    [notificationCenter
     addObserver: self
     selector:    @selector (handle_PlaybackStateChanged:)
     name:        MPMusicPlayerControllerPlaybackStateDidChangeNotification
     object:      musicPlayer];

    [musicPlayer beginGeneratingPlaybackNotifications];

并在通知中实施以下代码

- (void) handle_PlaybackStateChanged: (id) notification 
{

    MPMusicPlaybackState playbackState = [musicPlayer playbackState];

    if (playbackState == MPMusicPlaybackStatePaused) 
    {
           [self playiPodMusic];
    } 
    else if (playbackState == MPMusicPlaybackStatePlaying) 
    {

    } 
    else if (playbackState == MPMusicPlaybackStateStopped) 
    {
        [musicPlayer stop];
    }
}