Search code examples
swiftavfoundation

How to fix: "49: CreateDataFile failed"


I am trying to write a simple audio recorder in swift, following tutorials, but for some reason the recorder fails when running .record() and throws the following error

I have tried different settings for the file recording and changing the file location, no luck.

    let audioFilename = getFileURL(tag: tag)

    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 44100.0,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ] as [String : Any]

    do {

        audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record()}

Also the getFileURL methods:

func getFileURL(tag: Int) -> URL {

    let path = getDocumentsDirectory().appendingPathComponent("\(HelperFunctions.getRecordingName(tag: tag)).m4a")

    return path as URL

}
func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .applicationDirectory, in: .userDomainMask)
    return paths[0]
}

I get the "49: CreateDataFile failed" error where should be none


Solution

  • The "applicationDirectory" created the problem. Changing it to "documentDirectory" solved it.