简体   繁体   English

使用AVAudioPlayer延迟播放声音

[英]Delay in playing sounds using AVAudioPlayer

-(IBAction)playSound{ AVAudioPlayer *myExampleSound;

NSString *myExamplePath = [[NSBundle mainBundle] pathForResource:@"myaudiofile" ofType:@"caf"];

myExampleSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:myExamplePath] error:NULL];

myExampleSound.delegate = self;

[myExampleSound play];

}

I want to play a beep sound when a button is clicked. 我想在点击按钮时发出哔哔声。 I had used the above code. 我使用了上面的代码。 But it is taking some delay in playing the sound. 但播放声音需要一些延迟。

Anyone please help. 有人请帮忙。

There are two sources of the delay. 延迟有两个来源。 The first one is bigger and can be eliminated using the prepareToPlay method of AVAudioPlayer . 第一个更大,可以使用AVAudioPlayerprepareToPlay方法消除。 This means you have to declare myExampleSound as a class variable and initialize it some time before you are going to need it (and of course call the prepareToPlay after initialization): 这意味着您必须将myExampleSound声明为类变量并在需要它之前将其初始化一段时间(当然,在初始化之后调用prepareToPlay ):

- (void) viewDidLoadOrSomethingLikeThat
{
    NSString *myExamplePath = [[NSBundle mainBundle]
        pathForResource:@"myaudiofile" ofType:@"caf"];
    myExampleSound =[[AVAudioPlayer alloc] initWithContentsOfURL:
        [NSURL fileURLWithPath:myExamplePath] error:NULL];
    myExampleSound.delegate = self;
    [myExampleSound prepareToPlay];
}

- (IBAction) playSound {
    [myExampleSound play];
}

This should take the lag down to about 20 milliseconds, which is probably fine for your needs. 这应该延迟到大约20毫秒,这可能适合您的需要。 If not, you'll have to abandon AVAudioPlayer and switch to some other way of playing the sounds (like the Finch sound engine ). 如果没有,你将不得不放弃AVAudioPlayer并切换到其他播放声音的方式(如Finch声音引擎 )。

See also my own question about lags in AVAudioPlayer . 另请参阅我自己关于AVAudioPlayer滞后的问题。

AudioServicesPlaySystemSound is an option. AudioServicesPlaySystemSound是一个选项。 Tutorial here , sample code here . 教程这里 ,示例代码在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM