在Objective-C中播放没有延迟的声音效果

当用户在我的应用程序中按下某些button时,我想播放一些简单的声音效果,而且我尝试了几件事情,但是我总是得到延迟,导致声音看起来不同步。

我已经按照这里的教程,所以我已经尝试了audio服务中的构build,但有一个延迟,我试过AVAudioPlayer,但也有一个延迟,即使我使用“prepareToPlay”。

我是否真的必须安装像Finch这样庞大而凌乱的库才能在我的简单应用程序中获得简单的声音效果而无延迟?

希望你能为我澄清事情!

UPDATE

代码为audio服务:

NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"PlopsX4" withExtension:@"aif"]; AudioServicesCreateSystemSoundID((CFURLRef)soundURL, &sound1); AudioServicesPlaySystemSound(sound1); 

viewDidLoad中AVAudioPlayer的代码:

 NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"PlopsX4" withExtension:@"aif"]; self.avSound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil]; [self.avSound prepareToPlay] 

代码为AVAudioPlayer我想要播放文件的方法:

 [self.avSound play]; 

我得到这个工作的方式(我想我从另一篇文章中得到的主意)是创build一个空的1秒.wav文件,并在初始化时“播放”。 之后,当我打电话给其他音效时没有任何延迟。

在我的声音播放器对象中是这样的

  SystemSoundID blID; SystemSoundID cID; +(void)doInit { if (spinitialized){ AudioServicesPlaySystemSound (blID); return; } NSString *str = [[NSBundle mainBundle] pathForResource:@"ding.wav" ofType:@""]; NSURL *uref = [NSURL fileURLWithPath:str]; OSStatus error = AudioServicesCreateSystemSoundID ((CFURLRef)uref, &cID); if (error) NSLog(@"SoundPlayer doInit Error is %ld",error); str = [[NSBundle mainBundle] pathForResource:@"blank.wav" ofType:@""]; uref = [NSURL fileURLWithPath:str]; error = AudioServicesCreateSystemSoundID ((CFURLRef)uref, &blID); if (error) NSLog(@"SoundPlayer doInit Error is %ld",error); AudioServicesPlaySystemSound (blID); spinitialized = YES; } 

那么我可以毫不拖延地播放“丁”

  AudioServicesPlaySystemSound (cid); 

我最终做了类似于上面的麦克风。 我结束了在viewDidLoad中播放音量的声音:

 NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"PlopsX4" withExtension:@"aif"]; self.plops = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil]; [self.plops setVolume:0.0]; [self.plops play]; 

然后在我玩这个游戏的function上,我这样做:

 [self.plops setVolume:1.0]; [self.plops play]; 

有一件事情我发现,似乎有帮助的是,在进入可能播放声音的屏幕上播放声音的一小部分。 这似乎是“主要”声音机制 – 分配内部对象,分页等。

(我注意到这与Mike M的方法类似)。