![](/img/trans.png)
[英]What is the best way to play sound quickly upon fast button presses Xcode?
[英]What is the best way to play sound in a piano application?
我正在開發類似鋼琴的應用程序,並嘗試了兩個庫:
AudioToolbox / AudioToolbox.h
-(void)playSound :(NSString *)fName :(NSString *) ext{
SystemSoundID audioEffect;
NSString *path = [[NSBundle mainBundle] pathForResource : fName ofType :ext];
if ([[NSFileManager defaultManager] fileExistsAtPath : path]) {
NSURL *pathURL = [NSURL fileURLWithPath: path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
AudioServicesPlaySystemSound(audioEffect);
}
else {
NSLog(@"error, file not found: %@", path);
}
}
然后我會用類似
[self playSound:@"c_sharp" :@"mp3"];
這種方法的問題在於,當我按下調用playSound方法的按鈕時,會有1-2秒的延遲。 另外, AudioServicesPlaySystemSound似乎可以在系統音量上播放,如果禁用了該功能,則音量搖桿無法控制該音量。
我還嘗試了其他方法來播放聲音
AVFoundation / AVFoundation.h
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
-(void)viewDidLoad
{
[super viewDidLoad];
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *fileC2 = [mainBundle pathForResource:@"c_sharp" ofType:@"mp3"];
NSData *soundC2 = [NSData dataWithContentsOfFile:fileC2];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:soundC2
error:&error];
[self.audioPlayer prepareToPlay];
}
然后播放聲音,我會
- (IBAction)c_sharp_press:(UIButton *)sender {
[self.audioPlayer play];
}
這種方法的問題是我一次只能播放一種聲音。 如果我敲相同的鋼琴鍵,而不是添加另一個類似的聲音,則在第一個聲音播放完畢之前,它不會做任何事情。 也有一個小的1/2秒延遲。
我的問題是:
我使用什么庫來實現鋼琴鍵盤,以便:
請參閱Apple的loadPresetDemo示例代碼。 此代碼演示了如何將AUSampler Unit
與自定義音頻片段一起使用。 這是制作樂器類型應用程序的最佳方法,因為AUSampler
已針對響應性播放,低延遲,內存預加載和使用等進行了優化。在iOS中播放音頻的其他方法並不適合快速連續播放短聲音。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.