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
}
}
directoryURL
is proper, yet it appears mistaken forrecordingURL
. TherecordSettings
are coherent as well. Let me offer a working version.Swift 3
Legacy: Swift 2
► Find this solution on GitHub and additional details on Swift Recipes.