我一直在使用 Apple 闪亮的新AVFoundation
库,但到目前为止,我无法设置 an 使用的输入或输出设备(例如 USB 声卡)AVAudioEngine
,而且我似乎在文档中找不到任何内容说这甚至是可能的。
有人对这个有经验么?
我一直在使用 Apple 闪亮的新AVFoundation
库,但到目前为止,我无法设置 an 使用的输入或输出设备(例如 USB 声卡)AVAudioEngine
,而且我似乎在文档中找不到任何内容说这甚至是可能的。
有人对这个有经验么?
好的,在第十次重新阅读文档后,我注意到AVAudioEngine
有成员inputNode和outputNode(不知道我是怎么错过的!)。
以下代码似乎可以完成这项工作:
AudioDeviceID inputDeviceID = 53; // get this using AudioObjectGetPropertyData
AVAudioEngine *engine = [[AVAudioEngine alloc] init];
AudioUnit audioUnit = [[engine inputNode] audioUnit];
OSStatus error = AudioUnitSetProperty(audioUnit,
kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Global,
0,
&inputDeviceID,
sizeof(inputDeviceID));
我从CAPlayThrough示例中借用了非 AVFoundation C 代码。
这是一个完整的,如果有点粗糙,功能将播放一些音频用于测试目的(如果你没有在那里安装 GarageBand,请选择不同的文件,当然)。为避免对设备 ID 进行硬编码,它会切换到您可以在“系统偏好设置”中设置的警报(“声音效果”)设备。
AVAudioEngine *engine = [[AVAudioEngine alloc] init];
AudioUnit outputUnit = engine.outputNode.audioUnit;
OSStatus err = noErr;
AudioDeviceID outputDeviceID;
UInt32 propertySize;
AudioObjectPropertyAddress propertyAddress = {
kAudioHardwarePropertyDefaultSystemOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster };
propertySize = sizeof(outputDeviceID);
err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &propertySize, &outputDeviceID);
if (err) { NSLog(@"AudioHardwareGetProperty: %d", (int)err); return; }
err = AudioUnitSetProperty(outputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &outputDeviceID, sizeof(outputDeviceID));
if (err) { NSLog(@"AudioUnitSetProperty: %d", (int)err); return; }
NSURL *url = [NSURL URLWithString:@"/Applications/GarageBand.app/Contents/Frameworks/MAAlchemy.framework/Versions/A/Resources/Libraries/WaveNoise/Liquid.wav"];
NSError *error = nil;
AVAudioFile *file = [[AVAudioFile alloc] initForReading:url error:&error];
if (file == nil) { NSLog(@"AVAudioFile error: %@", error); return; }
AVAudioPlayerNode *player = [[AVAudioPlayerNode alloc] init];
[engine attachNode:player];
[engine connect:player to:engine.outputNode format:nil];
NSLog(@"engine: %@", engine);
if (![engine startAndReturnError:&error]) {
NSLog(@"engine failed to start: %@", error);
return;
}
[player scheduleFile:file atTime:[AVAudioTime timeWithHostTime:mach_absolute_time()] completionHandler:^{
NSLog(@"complete");
}];
[player play];