在iOS中多次播放声音的正确方式



我需要实现连续播放3次.aiff声音。声音长度是0.1毫秒,播放之间的间隔也应该是0.1毫秒。所以我决定用NSTimer来做。这是我的解决方案:

-(void)playSound{
    timerCounter = 0;
    timerForSound = [NSTimer scheduledTimerWithTimeInterval:0.2
                                                     target:self 
                                                   selector:@selector(playSoundThreeTimes)
                                                   userInfo:nil
                                                    repeats:YES];
}
-(void)playSoundThreeTimes{
    // play alert sound
    AudioServicesPlaySystemSound(beepSound);
    timerCounter++;
    if(timerCounter == 3){ // sound played 3 times
        [timerForSound invalidate];
        timerCounter = 0;
    }
}

问题是声音有时会滞后,即使我设置间隔0.25(0.2是因为声音长度+间隔=0.2)

有人能提出更好的方法吗?或者告诉我们问题可能是由什么引起的。

Artem

编辑:将此添加到异步线程也不起作用:

dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self playSound];
    });

我可能错了,但音频应该在它自己的线程上,但我不知道如何在ObjC中处理它(我用c++编程音频)。

NSTimer并不总是准确的,因为(我认为)它是一个消息线程。在高间隔(1秒以上)时,它不会引人注目,但在如此短的速度下,它可能会滞后。

两个原因:1.NSTimer并非100%准确。2.您正在主线程上触发事件,而主线程是UI的其余部分所在的位置。

就像亚当说的,你可以把它放在自己的线上。或者可以使用类似CADisplayLink的东西来代替NSTimer。

编辑:如果你是对的,罪魁祸首是AudioSystemServices。。。我不知道它是否有效,但你能尝试创建3个不同的哔哔声参考,然后调用哔哔声1、哔哔声2、哔哔声音3吗?因为我认为它可能在等待之前的声音停止。如果它不起作用,我想你可能需要使用音频队列或OpenAL。。。

试试这个:

-(void)playMyAudio {
    //play audio method
    if (loop<3) {   
        [self performSelector:@selector(playAudio) withObject:nil afterDelay:0.1];
        loop++;
    }
    else {
       loop = 0
    }
}

如果仍然滞后,我找到的唯一方法是创建3,4 AV播放器,并使用AVAudioSession 在FIFO模式下播放

最新更新