Search code examples
iphonexcode4.5

avoid Headset plugout stops AVAudioPlayer in iOS


In my iPhone app I am using AVAudioPlayer to play the songs...But when I plug out or plugin the headset during song playing, It automatically stops the AVAudioPlayer... I need to run audio player even though these changes occur.. any ideas will be appreciated.Thanks in advance.


Solution

  • I found the answer.

    Just we have to Import the followings

    #import <AudioToolbox/AudioToolbox.h>
    #import <AVFoundation/AVAudioPlayer.h>
    

    and write this code

    //Play the Event in Background
    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
    [[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
    newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
    

    Now its continuously playing even I plugged in&out the Ear phone.