将.m4a文件从磁盘加载到NSData对象 - iOS

时间:2014-08-18 09:39:53

标签: ios swift nsdata avaudiorecorder m4a

我用AVAudioRecorder录制了用户语音,并将其保存为文档文件夹中的.m4a文件。当我尝试将.m4a文件加载到NSData对象时,该对象为零 .m4a文件包含声音,使用的文件路径正确 我使用以下行加载.m4a文件:

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

3 个答案:

答案 0 :(得分:1)

AVAudioPlayer似乎需要一个带有“file://”前缀的路径,而SFileManager.defaultManager()。contentsAtPath()需要从路径中删除此前缀才能正常工作。尝试删除此操作:

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

答案 1 :(得分:0)

从文档:“如果path指定目录,或者发生其他错误,则此方法返回nil。”

检查文件的最佳方法是在Xcode:Menu Windows:Devices。选择连接到计算机的设备,双击应用程序,检查文件内容。

println(“sound path:(soundPath)”),投注不正确。

考虑使用NSData方法,它有一个错误参数来更好地报告失败:

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

错误报告示例:

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

示例错误消息:

  

错误:无法打开文件“TestSound.m4a”,因为没有   这样的文件。

BTW,路径名称更明确:声音可能是soundPath。

答案 2 :(得分:-1)

在尝试将网址加载到NSData之前释放AVAudioRecorder。