gpt4 book ai didi

ios - 使用AVAudioPlayer在后台播放声音序列

转载 作者:行者123 更新时间:2023-12-02 23:57:34 24 4
gpt4 key购买 nike

我想使用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函数。

最佳答案

音频 session 设置类别后的以下行解决了该问题:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

有关更多信息,请访问 https://stackoverflow.com/a/8071865/13441

关于ios - 使用AVAudioPlayer在后台播放声音序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13335940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com