1
votes

I am trying to let my program playing a recurring sound in background.

  1. add (Required Background Modes) property and (apps play audio) in info.plist.

  2. In my storyboard, app starts a UINarvigation controller with a root TableViewController. have #import in my Root TableViewController.m.

  3. 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];

  1. In doMyFunction method, I have playSystemSound(1003).

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.

1

1 Answers

2
votes

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];