objective-c - 如何更改声音的非实时音调/采样率?

标签 objective-c macos cocoa audio avfoundation

我有一个 mp3 声音,我想使用一次设置的平移、音高/采样率和音量控制来播放(不实时更改)。 我目前正在使用 AVAudioPlayer,它可以工作,但是速率设置执行时间拉伸(stretch)而不是执行采样率更改,其中较低的值会导致声音变得更慢和音调更低,而较高的值会导致声音变得更快和更高的音调(有点像磁带速度)。 例如,当您的声音实际为 44100 时,将采样率设置为 88200 HZ 将导致其以 200% 的速度/音调播放。 AVAudioPlayer 是否可以实现类似的功能,或者是否有其他方法可以实现此目的? 这是我到目前为止所拥有的:

player=[[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath: @"sound.mp3"] error: nil];
player.volume=0.4f;
player.pan=-1f;
player.enableRate=YES;
player.rate=2.0f;
[player play];

注意:我指的不是结合使用时间拉伸(stretch)来保持声音长度大致相同的音调方法,也不是任何“高级”算法。

最佳答案

AVAudioEngine 可以为您提供音高、速率、平移和音量控制:

self.engine = [[AVAudioEngine alloc] init];

NSError *error;

AVAudioPlayerNode *playerNode = [[AVAudioPlayerNode alloc] init];
AVAudioMixerNode *mixer = [[AVAudioMixerNode alloc] init];
AVAudioUnitVarispeed *varispeed = [[AVAudioUnitVarispeed alloc] init];

[self.engine attachNode:playerNode];
[self.engine attachNode:varispeed];
[self.engine attachNode:mixer];

[self.engine connect:playerNode to:varispeed format:nil];
[self.engine connect:varispeed to:mixer format:nil];
[self.engine connect:mixer to:self.engine.mainMixerNode format:nil];

BOOL result = [self.engine startAndReturnError: &error];
assert(result);

AVAudioFile *audioFile = [[AVAudioFile alloc] initForReading:url error:&error];
assert(audioFile);

// rate & pitch (fused), pan and volume controls
varispeed.rate = 0.5; // half pitch & rate
mixer.pan = -1;       // left speaker
mixer.volume = 0.5;   // half volume

[playerNode scheduleFile:audioFile atTime:nil completionHandler:nil];
[playerNode play];

如果您想要单独的速率和音调控制,请将 AVAudioUnitVarispeed 节点替换为 AVAudioUnitTimePitch 节点。

关于objective-c - 如何更改声音的非实时音调/采样率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65517928/

相关文章:

objective-c - 在另一种方法中添加事件指示器以避免挂起

macos - Mac OS X 下 Web 服务器的正确目录布局是什么?

cocoa - 接受文件: namesOfPromisedFilesDroppedAtDestination opens Finder window

cocoa - RestoreStateWithCoder 未在 NSView 中触发

ios - 如何根据互联网速度设置特定的视频质量

ios - 启用/禁用 UIButton 取决于 UITextField 中文本的长度

objective-c - 如何访问tableview单元格中的 subview

swift - nswindow 动画师无法在窗口 Controller 中工作

ios - `NSFormatter` 有多少个晦涩的子类?知道其他人吗?

ios - 通过 Cocoapods 安装 RestKit 0.20.0 后基础类型未知