smudis
smudis

Reputation: 399

Load .m4a file from disk into NSData object - iOS

I recorded the users voice with an AVAudioRecorder and saved it as a .m4a file in the documents folder. When I am trying to load the .m4a file into an NSDataobject, the object is nil.
The .m4a file contains sound and the used file path is correct.
I am using the following line to load the .m4a file:

let soundData = NSFileManager.defaultManager().contentsAtPath(soundPath)
println("\(soundData)") // prints nil  

Upvotes: 0

Views: 3344

Answers (3)

amurray4
amurray4

Reputation: 125

It appears that the AVAudioPlayer requires a path with a "file://" prefix, while SFileManager.defaultManager().contentsAtPath() needs this prefix removed from the path in order to work properly. Try removing this by doing something like:

soundPath = soundPath.stringByReplacingOccurrencesOfString("file://", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

Upvotes: 1

Matthew Klundt
Matthew Klundt

Reputation: 11

Release the AVAudioRecorder before trying to load the url to NSData.

Upvotes: 0

zaph
zaph

Reputation: 112857

From the docs: "If path specifies a directory, or if some other error occurs, this method returns nil."

The The best way to check for the file is in Xcode: Menu Windows:Devices. Select the device connected to the computer, double click the app, Examine the file contents.

println("sound path: (soundPath)"), bets are it is not correct.

Consider using the NSData method, it has an error parameter to better report a failure:

+ (id)dataWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)mask error:(NSError **)errorPtr

Example with error reporting:

let error:NSError
let soundData = NSData().contentsOfFile: soundPath options: 0 error: &errorPtr)
if soundData != nil {
    // Do something
}
else {
    println("error: \(error!.localizedDescription)")
}

Example error message:

error: The file “TestSound.m4a” couldn’t be opened because there is no such file.

BTW, a more clear name for the path: sound might be soundPath.

Upvotes: 0

Related Questions