List AudioInput Channels Swift

Viewed 196

I am trying to list all Input Channels for a USB Audio Device. Currently I am testing with a USB Headset which has 2 channels in and 2 out (I have confirmed this by checking the device in Audio Midi Setup) when I run the following code I only get one port. I think I need to create an AVCaptureConnection but I'm starting to get lost with all the different approaches I've found online.

Could someone help me out with a basic script that tells me how many channels I have on a USB Audio Input Device. Once I have achieved that I will want to monitor the incoming levels however I can figure that bit out

    let dev = AVCaptureDevice.default(for: AVMediaType.audio)
    let input = (try? AVCaptureDeviceInput.init(device: dev!))!
    let t = AVCaptureSession.init()
    t.addInput(input)
    print(t.inputs[0].ports.count) //Prints 1
1 Answers

t.inputs[0].ports are AVCaptureInput.Ports, which I believe represent streams of media on a single input, so unless you use a muxed device (one with video and audio, like an iPhone attached over USB) you're mostly going to see a count of 1 here.

Try looking instead at the formatDescription of the audio port, in your case:

print("channel count \(input.ports.first!.formatDescription!.audioStreamBasicDescription!.mChannelsPerFrame)")

Note that the above uses input directly, instead of t.inputs[0] which may not correspond to your USB Audio device AVCaptureDeviceInput if you ever add other inputs, like a webcam.

HOWEVER
If you're only interested in level monitoring, you can just use an AVCaptureAudioDataOutput:

self.audioOutput = AVCaptureAudioDataOutput()
session.AddInput(self.audioOutput)
session.startRunning()

// periodically consult averagePowerLevel and peakHoldLevel on channels of interest
self.audioOutputaudioOutput.connections.first!.audioChannels.first!.averagePowerLevel
Related