【问题标题】:What is the best way to play sound in a piano application?在钢琴应用程序中播放声音的最佳方式是什么?
【发布时间】:2013-06-08 22:46:59
【问题描述】:

我正在开发一个类似钢琴的应用程序并尝试了这两个库:

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. 我一次可以播放多个声音。

【问题讨论】:

  • 实现AudioQueues 和您的自定义波形/频率发生器功能。它会起作用,一旦你开始工作,它就会很好地工作,但这会很困难。

标签: ios audio


【解决方案1】:

查看 Apple 的 loadPresetDemo 的示例代码。此代码演示了如何将 AUSampler Unit 与自定义音频剪辑一起使用。这是制作乐器类应用程序的最佳方法,因为AUSampler 针对响应式播放、低延迟、内存预加载和使用等进行了优化。在 iOS 中播放音频的其他方法不太适合快速播放短声音继承。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    相关资源
    最近更新 更多