使用AVAudioPlayer延迟播放声音 [英] Delay in playing sounds using AVAudioPlayer
问题描述
- (IBAction)playSound {AVAudioPlayer * myExampleSound;
NSString * myExamplePath = [[NSBundle mainBundle] pathForResource:@myaudiofileofType:@caf];
myExampleSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:myExamplePath] error:NULL];
myExampleSound.delegate = self;
[myExampleSound play];
}
我想在按钮被点击时发出蜂鸣声。我使用了上面的代码。
任何人请帮助。 div>
延迟有两个来源。第一个更大,可以使用 AVAudioPlayer
的 prepareToPlay
方法消除。这意味着您必须将 myExampleSound
声明为类变量,并在您需要它之前初始化一段时间(当然也可以调用 prepareToPlay
初始化后):
- (void)viewDidLoadOrSomethingLikeThat
{
NSString * myExamplePath = [[NSBundle mainBundle]
pathForResource:@myaudiofileofType:@caf];
myExampleSound = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:myExamplePath] error:NULL];
myExampleSound.delegate = self;
[myExampleSound prepareToPlay];
}
- (IBAction)playSound {
[myExampleSound play];
}
这应该需要延迟到约20毫秒,这可能是你的需要。如果没有,你必须放弃 AVAudioPlayer
,并切换到播放声音的其他方式(如 Finch音效引擎)。
另请参阅我自己的关于在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
. 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):
- (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. If not, you’ll have to abandon AVAudioPlayer
and switch to some other way of playing the sounds (like the Finch sound engine).
See also my own question about lags in AVAudioPlayer.
这篇关于使用AVAudioPlayer延迟播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!