isa*_*thg 3 iphone cocoa-touch objective-c 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];
}
Run Code Online (Sandbox Code Playgroud)
我想在点击按钮时发出哔哔声.我使用了上面的代码.但播放声音需要一些延迟.
有人请帮忙.
延迟有两个来源.第一个更大,可以使用prepareToPlay方法消除AVAudioPlayer.这意味着您必须声明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];
}
Run Code Online (Sandbox Code Playgroud)
这应该延迟到大约20毫秒,这可能适合您的需要.如果没有,你将不得不放弃AVAudioPlayer并切换到播放声音的其他方式(如Finch声音引擎).
另请参阅我自己关于AVAudioPlayer滞后的问题.
| 归档时间: |
|
| 查看次数: |
6541 次 |
| 最近记录: |