Member-only story

Accessing Samples from Mic in iOS Swift and SwiftUI

Todd Dalton
2 min read5 days ago

It took ages to find out this. All the code I found was incomplete and caused errors like any of the following:

* required condition is false: !IsInternalNode(node)

or

* required condition is false format.sampleRate == hwFormat.sampleRate

or

* required condition is false: IsFormatSampleRateAndChannelCountValid(hwFormat)

or

* required condition is false: [AVAudioEngine.mm:573:AttachNode: (!IsInternalNode(node))]

So here’s my code which came from loads of different places and (through gritted teeth) I used AI. All sources had grains of truth in them but I needed to bring them all together to get a result:



import SwiftUI
import CoreAudio
import AVFoundation

struct ContentView: View {
// Get an instance of an AudioEngine
var engine: AVAudioEngine = AVAudioEngine()
// This is the shared instance that seems to provide all the metadata like frames and sample rate
var aSession: AVAudioSession = AVAudioSession.sharedInstance()
// This AudioNode will be used to grab the data from the mic
@State var inputNode: AVAudioNode?
// I use this to indicated that the sampling has started and so can adjust UI, etc.
@State var started: Bool = false
// Just for demo purposes to output to the screen
@State var text: String = "--"
// Bool to indicate the user has granted use of the mic to the app
@State var granted: Bool = false

// This will start the sampling
func start() {
guard !started && granted else { return }

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Todd Dalton
Todd Dalton

Written by Todd Dalton

Avid, PPro, DaVinci. Swift, Obj-C, Java, PHP.

No responses yet

Write a response