How to play an audio file in the background?

How to play an audio file in the background?

This is my code:

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@"caf"];
    NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
    NSError *audioError = nil;

    alarmAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
    [sampleData release];
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];



    if(audioError != nil) {
        NSLog(@"An audio error occurred: \"%@\"", audioError);
    }
    else {
        [alarmAudioPlayer setNumberOfLoops: -1];
        [alarmAudioPlayer play];
    }

    }

But it does not continue to play when I'm multitasking, but then resumes when I multitask back to the application.

Note. I know this is a duplicate of the old question, but this answer did not work for me.

+3
source share
1 answer

Make sure you install the app to use the background audio API. Add this entry to your application Info.plist:

enter image description here

+4
source

All Articles