Skip to content

Instantly share code, notes, and snippets.

@narner
Created October 23, 2019 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save narner/7333eee65e52e3c462a1b28e09b61407 to your computer and use it in GitHub Desktop.
Save narner/7333eee65e52e3c462a1b28e09b61407 to your computer and use it in GitHub Desktop.
func startAudioEngine() {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(
AVAudioSession.Category.record)
} catch let error as NSError {
print("audioSession error: \(error.localizedDescription)")
}
// Create a new audio engine.
audioEngine = AVAudioEngine()
//https://forums.developer.apple.com/thread/44833
audioEngine.mainMixerNode
do {
// Start the stream of audio data.
try audioEngine.start()
} catch {
print("Unable to start AVAudioEngine: \(error.localizedDescription)")
}
// Get the native audio format of the engine's input bus.
let inputFormat = audioEngine.inputNode.inputFormat(forBus: 0)
// Create a new stream analyzer.
print(inputFormat)
let streamAnalyzer = SNAudioStreamAnalyzer(format: inputFormat)
// Create a new observer that will be notified of analysis results.
// Keep a strong reference to this object.
let resultsObserver = ResultsObserver()
do {
// Prepare a new request for the trained model.
let request = try SNClassifySoundRequest(mlModel: model)
try streamAnalyzer.add(request, withObserver: resultsObserver)
} catch {
print("Unable to prepare request: \(error.localizedDescription)")
return
}
// Serial dispatch queue used to analyze incoming audio buffers.
let analysisQueue = DispatchQueue(label: "com.apple.AnalysisQueue")
// Install an audio tap on the audio engine's input node.
audioEngine.inputNode.installTap(onBus: 0,
bufferSize: 8192, // 8k buffer
format: inputFormat) { buffer, time in
// Analyze the current audio buffer.
analysisQueue.async {
streamAnalyzer.analyze(buffer, atAudioFramePosition: time.sampleTime)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment