Created
October 23, 2019 23:38
-
-
Save narner/7333eee65e52e3c462a1b28e09b61407 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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