我想用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
函数。
答案 0 :(得分:0)
音频会话设置类别后面的以下行解决了问题:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
的更多信息