2009-12-02 57 views
16

Tôi hiện đang làm việc trên một dự án liên quan đến chơi nhạc từ thư viện nhạc iphone trong ứng dụng bên trong. Tôi đang sử dụng MPMediaPickerController để cho phép người dùng chọn nhạc của họ và phát nhạc bằng trình phát nhạc iPod trong iPhone.Làm thế nào để lập trình phát hiện tai nghe trong iphone?

Tuy nhiên, tôi gặp sự cố khi người dùng lắp tai nghe và tháo tai nghe. Âm nhạc đột nhiên ngừng chơi mà không có lý do gì. Sau khi thử nghiệm một số, tôi phát hiện ra rằng máy nghe nhạc iPod sẽ tạm dừng chơi khi người dùng rút phích cắm tai nghe của mình ra khỏi thiết bị. Vì vậy, có cách nào để lập trình phát hiện nếu tai nghe đã được rút ra để tôi có thể tiếp tục chơi nhạc? Hoặc là có cách nào để ngăn chặn máy nghe nhạc iPod từ tạm dừng khi người dùng rút phích cắm tai nghe của mình?

Trả lời

9

Bạn nên đăng ký cho AudioRoute thay đổi thông báo và thực hiện như thế nào bạn muốn xử lý rout thay đổi

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

và trong cuộc gọi lại, bạn có thể biết lý do thay đổi tuyến đường

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..     
    } 
+0

erm tôi đang gặp 2 lỗi khi biên dịch 1) inPropertyValue của wat? Nó không bị suy giảm hoặc trong tham số phương thức 2) CFDictionaryGetValue trả về một con trỏ void không tương thích với CFNumberRef. Tôi có cần làm bất kỳ việc đúc nào trước khi trả lại giá trị không? –

+0

hmm tôi quản lý để biên dịch mã của tôi và tất cả mọi thứ chạy tốt nhưng khi tôi cắm vào hoặc rút phích cắm tai nghe của tôi không có gì xảy ra. Hàm audioRouteChangeListenerCallback không được gọi. Có điều gì khác tôi đang thiếu bên cạnh các chức năng trên không? –

+0

Bạn nên đăng ký cho chức năng nghe sau khi cuộc gọi của bạn để khởi tạo AudioSession .. Bạn có làm theo cách đó không? – prakash

2

Tôi thấy bạn đang sử dụng MPMediaPlayer Framework tuy nhiên việc xử lý micrô được thực hiện bằng cách sử dụng khung công tác AVAudioPlayer, mà bạn sẽ cần phải thêm vào dự án của mình.

Trang web của Apple có mã từ khung AVAudioPlayer mà tôi sử dụng để xử lý các gián đoạn từ người dùng cắm vào hoặc tháo tai nghe micrô của Apple.

Kiểm tra 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]; 
    } 
} 

Mã của tôi là một chút khác nhau và một số những điều này có thể giúp bạn:

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]; 
    } 
} 
4

Nếu bạn chỉ muốn kiểm tra xem tai nghe được cắm vào bất cứ lúc nào, mà không cần nghe những thay đổi lộ trình, bạn chỉ có thể làm như sau:

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); 
} 

Chúc mừng, Raffaello Colasante

+1

Triển khai tốt hơn nhiều việc này có thể tìm thấy tại đây: http://stackoverflow.com/questions/3728781/detect-if-headphones-not-microphone-are-plugged- thiết bị ios-to-an-ios –

2

Hey các bạn chỉ cần kiểm tra ứng dụng mẫu AddMusic. Sẽ giải quyết tất cả các vấn đề liên quan đến iPod của bạn

Đầu tiên đăng ký máy nghe nhạc iPod để thông báo với mã sau đây

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 

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

    [musicPlayer beginGeneratingPlaybackNotifications]; 

Và thực hiện đoạn mã sau trong thông báo

- (void) handle_PlaybackStateChanged: (id) notification 
{ 

    MPMusicPlaybackState playbackState = [musicPlayer playbackState]; 

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

    } 
    else if (playbackState == MPMusicPlaybackStateStopped) 
    { 
     [musicPlayer stop]; 
    } 
} 
Các vấn đề liên quan