Kevin Machado
Kevin Machado

Reputation: 4187

AVAudioRecorder settings empty after constructor call

I'm trying to record audio using the microphone and AVAudioRecorder.

It works on iOS 8 but my code does not work anymore on iOS 9.

The recordSettings dictionary is set properly, then I give it to the AVAudioRecorder:URL:settings constructor.

But, just after, recorder.settings is empty, an assertion failure is thrown

let recordSettings: [String: AnyObject] = [
            AVNumberOfChannelsKey: NSNumber(integer: 2),
            AVFormatIDKey: NSNumber(integer: Int(kAudioFormatMPEG4AAC)),
            AVEncoderBitRateKey: NSNumber(integer: 64)]

var recorder: AVAudioRecorder!
do {
     recorder = try AVAudioRecorder(URL: tempURL, settings:recordSettings) // recordSettings.count = 3
     assert(recorder.settings.count != 0, "Audio Recorder does not provide settings") // assertion failure threw
} catch let error as NSError {
     print("error when intitializing recorder: \(error)")
     return
}

Anyone can help me ? Is it a bug ?

EDIT : In my entire code I did not test recorder.settings just after. I did instantiate recorder like my code above, then I did that :

recorder.delegate = self
recorder.prepareToRecord()
recorder.meteringEnabled = true

And it crashes in this line :

for i in 1...(recorder.settings[AVNumberOfChannelsKey] as! Int) {
    ...
}

It crashes because recorder.settings[AVNumberOfChannelsKey] is nil

Upvotes: 0

Views: 194

Answers (1)

Gordon Childs
Gordon Childs

Reputation: 36072

I'm not sure why you're checking the settings property, but from the AVAudioRecorder header file, on the settings property:

these settings are fully valid only when prepareToRecord has been called

so you must call prepareToRecord() first BUT it will fail/return false, because your bitrate is way too low! Its unit is bits per second, not kilobits per second:

AVEncoderBitRateKey: NSNumber(integer: 64000)

This worked on iOS 8 because your too-low bitrate was simply discarded. Looks like it became an error in iOS 9.

Upvotes: 1

Related Questions