4
-(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];

}

我想在单击按钮时播放哔声。我已经使用了上面的代码。但是播放声音需要一些延迟。

任何人请帮忙。

4

2 回答 2

9

延迟有两个来源。第一个较大,可以使用 的prepareToPlay方法消除AVAudioPlayer。这意味着您必须声明myExampleSound为类变量并在需要它之前对其进行初始化(当然还要调用prepareToPlayafter 初始化):

- (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];
}

这应该会将延迟降低到大约 20 毫秒,这可能适合您的需求。如果没有,您将不得不放弃AVAudioPlayer并切换到其他播放声音的方式(如Finch 声音引擎)。

另请参阅我自己关于AVAudioPlayer 滞后的问题。

于 2010-03-31T06:27:03.517 回答
1

AudioServicesPlaySystemSound是一种选择。教程在这里,示例代码在这里

于 2010-03-31T06:34:17.213 回答