Playing sequence of sounds in background with AVAudioPlayer

血红的双手。 提交于 2019-12-08 05:34:21

问题


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.


回答1:


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

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

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



来源:https://stackoverflow.com/questions/13335940/playing-sequence-of-sounds-in-background-with-avaudioplayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!