Install AVAudioEngine input and output devices

I played with Apple's new shiny new AVFoundation library, but so far I have not been able to install the input or output devices (such as a USB sound card) used by AVAudioEngine , and I can't seem to find anything in the documentation to say it is possible.

Does anyone have any experience?

+5
source share
2 answers

Well, after re-reading the documents for the 10th time, I noticed that AVAudioEngine has inputNode and outputNode members (I don’t know how I missed this!).

The following code seems to do the job:

 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)); 

I borrowed non-AVFoundation C code from the CAPlayThrough example.

+2
source

Here is a complete, if somewhat crude function that will play some kind of sound for testing (select another file if you do not have GarageBand installed there). To avoid hard coding of the device identifier, it switches to your notification device (“sound effects”), which you can set in the system settings.

 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]; 
+2
source

Source: https://habr.com/ru/post/1214376/


All Articles