Created
May 31, 2019 13:06
-
-
Save etelford/3a5d1c3451368e5d1775617c2c05d571 to your computer and use it in GitHub Desktop.
iOS: Recording audio from the mic & saving it to a file
This file contains 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
// Recording audio to a file: | |
var engine = AVAudioEngine() | |
var distortion = AVAudioUnitDistortion() | |
var reverb = AVAudioUnitReverb() | |
var audioBuffer = AVAudioPCMBuffer() | |
var outputFile = AVAudioFile() | |
var delay = AVAudioUnitDelay() | |
func initializeAudioEngine() { | |
engine.stop() | |
engine.reset() | |
engine = AVAudioEngine() | |
isRealTime = true | |
do { | |
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord) | |
let ioBufferDuration = 128.0 / 44100.0 | |
try AVAudioSession.sharedInstance().setPreferredIOBufferDuration(ioBufferDuration) | |
} catch { | |
assertionFailure("AVAudioSession setup error: \(error)") | |
} | |
let fileUrl = URLFor("/NewRecording.caf") | |
print(fileUrl) | |
do { | |
try outputFile = AVAudioFile(forWriting: fileUrl!, settings: engine.mainMixerNode.outputFormatForBus(0).settings) | |
} | |
catch { | |
} | |
let input = engine.inputNode! | |
let format = input.inputFormatForBus(0) | |
//settings for reverb | |
reverb.loadFactoryPreset(.MediumChamber) | |
reverb.wetDryMix = 40 //0-100 range | |
engine.attachNode(reverb) | |
delay.delayTime = 0.2 // 0-2 range | |
engine.attachNode(delay) | |
//settings for distortion | |
distortion.loadFactoryPreset(.DrumsBitBrush) | |
distortion.wetDryMix = 20 //0-100 range | |
engine.attachNode(distortion) | |
engine.connect(input, to: reverb, format: format) | |
engine.connect(reverb, to: distortion, format: format) | |
engine.connect(distortion, to: delay, format: format) | |
engine.connect(delay, to: engine.mainMixerNode, format: format) | |
assert(engine.inputNode != nil) | |
isReverbOn = false | |
try! engine.start() | |
} | |
func startRecording() { | |
let mixer = engine.mainMixerNode | |
let format = mixer.outputFormatForBus(0) | |
mixer.installTapOnBus(0, bufferSize: 1024, format: format, block: | |
{ (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in | |
print(NSString(string: "writing")) | |
do { | |
try self.outputFile.writeFromBuffer(buffer) | |
} | |
catch { | |
print(NSString(string: "Write failed")); | |
} | |
}) | |
} | |
func stopRecording() { | |
engine.mainMixerNode.removeTapOnBus(0) | |
engine.stop() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment