簡體   English   中英

在鋼琴應用程序中播放聲音的最佳方法是什么?

[英]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秒延遲。


我的問題是:

我使用什么庫來實現鋼琴鍵盤,以便:

  1. 播放聲音沒有或沒有明顯的延遲。
  2. 聲音由音量鍵控制。
  3. 我一次可以播放多個聲音。

請參閱Apple的loadPresetDemo示例代碼。 此代碼演示了如何將AUSampler Unit與自定義音頻片段一起使用。 這是制作樂器類型應用程序的最佳方法,因為AUSampler已針對響應性播放,低延遲,內存預加載和使用等進行了優化。在iOS中播放音頻的其他方法並不適合快速連續播放短聲音。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM