Reputation: 327
I am trying to let my program playing a recurring sound in background.
add (Required Background Modes) property and (apps play audio) in info.plist.
In my storyboard, app starts a UINarvigation controller with a root TableViewController. have #import in my Root TableViewController.m.
There is a NSTimer property, my_timer, in my Root TableViewController. I set it in viewDidLoad method as following:
my_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector: @selector(doMyFunction) userInfo:nil repeats:YES];
My app plays sounds periodically as expected when in front mode, but never gets played in back ground mode. I can't figure out what is done not correctly, thank for your help.
Upvotes: 1
Views: 1170
Reputation: 1364
playSystemSound will never play audio in background. To do that call this function in your main source code, just afer ViewDidLoad:
-(void)createAudioSession
{
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// Use this code instead to allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
NSError *myErr;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&myErr];
}
Then
AVAudioPlayer * FXPlayer;
FXPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:resourcePath] error:&err];
FXPlayer.numberOfLoops = -1; // will loop forever
[FXPlayer play];
Upvotes: 2