4
votes

I'm trying to make a simple voice recorder. I'm using Xcode-beta 7 and I've based my code off of these three sources.

I'm using the following code:

var recordSettings = [
        AVFormatIDKey: kAudioFormatAppleIMA4,
        AVLinearPCMIsBigEndianKey: 0,
        AVLinearPCMIsFloatKey: 0,
        AVNumberOfChannelsKey: 2,
        AVSampleRateKey: 32000
    ]

    var session = AVAudioSession.sharedInstance()

    do{
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        recorder = AVAudioRecorder(URL: filePath, settings: recordSettings, error: nil)
    }catch{
        print("Error")
    }

but it says that "Cannot find an initializer for type 'AVAudioRecorder' that accepts an argument list of type '(URL:NSURL?, settings:[String:AudioFormatID], error:nil)'"

Aren't my inputs exactly what the documentation asks for?

2
I'm having this EXACT same problem right now! When I create the recordSettings dictionary I get an error "AudioFormatID does not conform to protocol 'AnyObject'". Are you having that issue too?Hundley
because you are passing Int and not object. Try to create an NSNumber instead like I show in my answer: NSNumber(integer: kAudioFormatAppleIMA4)Lory Huz

2 Answers

3
votes

AVAudioRecorder does not need anymore the error parameter:

init(URL url: NSURL, settings settings: [String : AnyObject]) throws

Also, I needed to unwrap the filePath, as suggested in a previous answer:

func recordSound(){
    let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

    let recordingName = "my_audio.wav"
    let pathArray = [dirPath, recordingName]
    let filePath = NSURL.fileURLWithPathComponents(pathArray)
    let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue,
            AVEncoderBitRateKey: 16,
            AVNumberOfChannelsKey: 2,
            AVSampleRateKey: 44100.0]
    print(filePath)

    let session = AVAudioSession.sharedInstance()
    do {
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        audioRecorder = try AVAudioRecorder(URL: filePath!, settings: recordSettings as! [String : AnyObject])
    } catch _ {
        print("Error")
    }

    audioRecorder.delegate = self
    audioRecorder.meteringEnabled = true
    audioRecorder.prepareToRecord()
    audioRecorder.record()
}
0
votes

Your filePath is wrapped as an optionnal. You should check if isn't nil and unwrap it like this:

recorder = AVAudioRecorder(URL: filePath!, settings: recordSettings, error: nil)

And you need to pass an NSError pointer too:

var error: NSError?
recorder = AVAudioRecorder(URL: filePath!, settings: recordSettings, error: &error)

After that, if you have error in your settings dictionnay, try to transform all Tnt to NSNumber, because NSNumber is an Object, not Int. Example:

NSNumber(integer: kAudioFormatAppleIMA4)