Using AVAudioRecorder to record voice

3.5k views Asked by At

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

There are 2 answers

5
Laura Calinoiu On BEST ANSWER

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()
}
1
Lory Huz On

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)