播放声音的序列中的背景AVAudioPlayer [英] Playing sequence of sounds in background with AVAudioPlayer

查看:124
本文介绍了播放声音的序列中的背景AVAudioPlayer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想播放声音的序列与 AVAudioPlayer 。所有的都在前景好,但在后台我有问题。

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.

如何解决这个问题?

其实,我有声音的序列和启动的时刻序列。当用户触控按键应用程序启动时播放声音。

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

我用下面的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 函数被调用完成声音播放结束后的每一次。

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

推荐答案

在音频会话设置类别下面这行解决了这个问题:

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

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

http://stackoverflow.com/a/8071865/13441

这篇关于播放声音的序列中的背景AVAudioPlayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆