1

I want to play sequence of sounds with AVAudioPlayer. All are ok in foreground, but in background I have issues.

After scheduling next sound it plays in background, but initialisation of sound after next fails.

How to resolve this issue?

In fact, I have sequence of sounds and sequence of starting moments. When user touch button application starts play sounds.

I use the following code:

- (void)soundScheduleNext
{
    NSURL * url = ...; // get url of next sound file

    if (soundPlayer == nil)
        soundPlayer = [AVAudioPlayer alloc];
    soundPlayer = [soundPlayer initWithContentsOfURL:url error:nil];
    soundPlayer.delegate = self;

    AVAudioSession * audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

    // if this is a first element of sound sequence...
    if (soundSeqNext == 0)
    {
        // ... play right now
        [soundPlayer prepareToPlay];
        soundStartMoment = [soundPlayer deviceCurrentTime];

        [soundPlayer play];
    } else {
        BOOL prepareToPlayOk = [soundPlayer prepareToPlay];

        // when second element of sequence play - prepareToPlayOk is YES; when third - prepareToPlayOk is NO :(
        NSLog(@"soundScheduleNext: prepareToPlayOk = %d", (int)prepareToPlayOk, nil);

        NSTimeInterval timeMoment = ... ; // get moment of time for next sound
        [soundPlayer playAtTime:timeMoment];
    }
    soundSeqNext++;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self soundScheduleNext];
}

audioPlayerDidFinishPlaying function is called every time after end of sound playback finished.

sergtk
  • 10,714
  • 15
  • 75
  • 130

1 Answers1

0

The following line after audio session setting category solves the problem:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

More info at https://stackoverflow.com/a/8071865/13441

Community
  • 1
  • 1
sergtk
  • 10,714
  • 15
  • 75
  • 130