Search code examples
iosswift2avaudiorecorder

AVAudioRecorder swift 2


I had my AVAudioRecorder working, but since upgrading to swift 2, I can't seem to figure out how to configure it correctly. I keep getting an error saying the AVAudioRecorder initializer cannot be invoked, but the parameters I'm providing look correct to me.

var recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
    AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
    AVNumberOfChannelsKey : NSNumber(int: 1),
    AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Medium.rawValue))]


var recordingURL: NSURL? = nil
var audioRecorder:AVAudioRecorder!


func directoryURL() -> NSURL? {

    let fileManager = NSFileManager.defaultManager()
    let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    let documentDirectory = urls[0] as NSURL
    let soundURL = documentDirectory.URLByAppendingPathComponent("sound.m4a")
    return soundURL 
}

@IBAction func recordPressed(sender: AnyObject) {

    let audioSession: AVAudioSession = AVAudioSession.sharedInstance()

    do {
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
    } catch _ {
    }

    do {
        try audioSession.setActive(true)
    } catch _ {
    }

    var error: NSError?

    audioRecorder = AVAudioRecorder(URL: recordingURL, settings: recordSettings, error: &error)

    if let e = error {

        print(e.localizedDescription, terminator: "")
    }
    else
    {
        audioRecorder.record()
        self.stopButton.enabled = true
        self.playButton.enabled = false
        self.recordButton.enabled = false

    }


}

Solution

  • directoryURL is proper, yet it appears mistaken for recordingURL. The recordSettings are coherent as well. Let me offer a working version.

    Swift 3

    var audioRecorder:AVAudioRecorder!
    
    let recordSettings = [
        AVSampleRateKey : NSNumber(value: Float(44100.0)),
        AVFormatIDKey : NSNumber(value:Int32(kAudioFormatMPEG4AAC)),
        AVNumberOfChannelsKey : NSNumber(value: Int32(1)),
        AVEncoderAudioQualityKey :
            NSNumber(value: Int32(AVAudioQuality.medium.rawValue))]
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
            try audioRecorder = AVAudioRecorder(url: directoryURL()!,
                                                settings: recordSettings)
            audioRecorder.prepareToRecord()
        } catch {}
    }
    
    func directoryURL() -> URL? {
        let fileManager = FileManager.default
        let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
        let documentDirectory = urls[0] as URL
        let soundURL = documentDirectory.appendingPathComponent("sound.m4a")
        return soundURL
    }
    
    @IBAction func doRecordAction(_ sender: AnyObject) {
        if !audioRecorder.isRecording {
            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setActive(true)
                audioRecorder.record()
            } catch {}
        }
    }
    
    @IBAction func doStopAction(_ sender: AnyObject) {
        audioRecorder.stop()
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setActive(false)
        } catch {}
    }
    

    Legacy: Swift 2

    var audioRecorder:AVAudioRecorder!
    
    let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
        AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
        AVNumberOfChannelsKey : NSNumber(int: 1),
        AVEncoderAudioQualityKey :
            NSNumber(int: Int32(AVAudioQuality.Medium.rawValue))]
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
            try audioRecorder = AVAudioRecorder(URL: self.directoryURL()!,
                settings: recordSettings)
            audioRecorder.prepareToRecord()
        } catch {}
    }
    
    func directoryURL() -> NSURL? {
        let fileManager = NSFileManager.defaultManager()
        let urls = fileManager.URLsForDirectory(.DocumentDirectory,
                                                inDomains: .UserDomainMask)
        let documentDirectory = urls[0] as NSURL
        let soundURL = documentDirectory.URLByAppendingPathComponent("sound.m4a")
        return soundURL 
    }
    
    @IBAction func doRecordAction(sender: AnyObject) {
        if !audioRecorder.recording {
            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setActive(true)
                audioRecorder.record()
            } catch {}
        }
    }
    
    @IBAction func doStopAction(sender: AnyObject) {
        audioRecorder.stop()
        let audioSession = AVAudioSession.sharedInstance()
    
        do {
            try audioSession.setActive(false)
        } catch {}
    }
    

    ► Find this solution on GitHub and additional details on Swift Recipes.