我想用 播放声音序列AVAudioPlayer
。前台一切正常,但在后台我有问题。
安排下一个声音后,它会在后台播放,但下一个声音初始化失败。
如何解决这个问题?
事实上,我有声音序列和起始时刻序列。当用户触摸按钮应用程序开始播放声音时。
我使用以下代码:
- (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
每次声音播放结束后都会调用该函数。