简体   繁体   中英

How to play a audio file in the background?

How can I 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 doesn't continue playing when I multitask, but then resumes when I multitask back to the app.

Note: I know this is a duplicate of a old question but that answer didn't work for me.

Make sure you have set your application to utilize the background audio API. Add this entry in your app's Info.plist :

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM