4

I'm trying to use AVAudioEngine to record sounds from the microphone together with various sound effect files to a AVAudioFile.

I create an AVAudioFile like this:

let settings = self.engine.mainMixerNode.outputFormatForBus(0).settings
try self.audioFile = AVAudioFile(forWriting: self.audioURL, settings: settings, commonFormat: .PCMFormatFloat32, interleaved: false)

I install a tap on the audio engine's mainMixerNode, where I write the buffer to the file:

self.engine.mainMixerNode.installTapOnBus(0, bufferSize: 4096, format: self.engine.mainMixerNode.outputFormatForBus(0)) { (buffer, time) -> Void in
    do {
        try self.audioFile?.writeFromBuffer(buffer)
    } catch let error as NSError {
        NSLog("Error writing %@", error.localizedDescription)
    }
}

I'm using self.engine.mainMixerNode.outputFormatForBus(0).settingswhen creating the audio file since Apple states that "The buffer format MUST match the file's processing format which is why outputFormatForBus: was used when creating the AVAudioFile object above". In the documentation for installTapOnBus they also say this: " The tap and connection formats (if non-nil) on the specified bus should be identical"

However, this gives me a very large, uncompressed audio file. I want to save the file as .m4a but don't understand where to specify the settings I want to use:

[
    AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatMPEG4AAC),
    AVSampleRateKey : NSNumber(double: 32000.0), //44100.0
    AVNumberOfChannelsKey: NSNumber(int: 1),
    AVEncoderBitRatePerChannelKey: NSNumber(int: 16),
    AVEncoderAudioQualityKey: NSNumber(int: Int32(AVAudioQuality.High.rawValue))
]

If I pass in these settings instead when creating the audio file, the app crashes when I record.

Any suggestions or ideas on how to solve this?

rodskagg
  • 3,827
  • 4
  • 27
  • 46
  • 1
    Did you ever figure this out? – user3344977 Mar 13 '16 at 07:34
  • @user3344977 I decided to record to a .caf file and then export the file to a compressed file after recording is done. – rodskagg Mar 13 '16 at 08:49
  • 1
    Would you be willing to share some code on github, or respond to a stackoverflow question? I'm totally stuck. I can get correct playback with effects, even save microphone file in realtime with effects, but can't get it to work with AVAudioUnitTimePitch for some reason. – user3344977 Mar 13 '16 at 08:54

0 Answers0