Hein Htet Zaw
Hein Htet Zaw

Reputation: 41

AVAudioPlayer background task is not working on iOS 5.0.1 device but it is working on iOS 5 Simulator

I am doing sample application that play a song and that song will still playing even the application goes background.

In iOS 5 xcode simulator, it still play the song when app goes to background but when I run on iOS 5.0.1 iPad2 device, app stop playing sound when it goes to background. The following are the code to play a song and do background task. Do you face this kind of issue in iOS 5.0.1? or am I missing something in code? But I am wondering how it is working in simulator?

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"01-Track" ofType:@"mp3"]];
    NSError *error;
    audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
    if(error)
    {
        NSLog(@"Error in audio palyer: %@", [error localizedDescription]);
    }
    else
    {
        audioPlayer.delegate =self;
        [audioPlayer prepareToPlay];
        trackControl.maximumValue=[audioPlayer duration];
        trackControl.value=0.0;

        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [[AVAudioSession sharedInstance] setActive: YES error: nil];
    }
}
-(IBAction)playAudio:(id)sender
{
     UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
     if([audioPlayer play]){
      newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
}

Thanks!

Upvotes: 2

Views: 1890

Answers (1)

Siddharth
Siddharth

Reputation: 555

For audio to continue working in background you should add a key called Required Background Modes in your info.plist with value App plays audio.But it's use is not very much promoted by apple unless it's absolutely necessary.

Upvotes: 2

Related Questions