尝试播放录制的文件时文件路径不正确

时间:2015-08-11 08:26:47

标签: ios swift core-data

我有一个AVAudioRecorder:

let dirPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let docsDir = dirPaths[0] as! String
let soundFilePath = docsDir.stringByAppendingPathComponent("sound.caf")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath)

do {

        try audioRecorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
        audioRecorder?.prepareToRecord()

    } catch let error as NSError {

        print("audioSession error: \(error.localizedDescription)")
        audioRecorder = nil

    }

然后记录并将文件URL保存到核心数据中,因为我无法将URL保存到核心数据,所以我使用字符串作为文件路径:

content.setValue(path, forKey: "fileDirectory")

记录器肯定创建了一个文件,因为它显示在表视图中。但它无法播放,因此我检查文件是否存在于提供的文件路径中:

if audioRecorder?.recording == false {

        let inspirationString = inspirations[indexPath.row].valueForKey("fileDirectory") as! String
        let fileDirString = NSURL(string: inspirationString)!

        if !NSFileManager.defaultManager().fileExistsAtPath(inspirationString) {

            print(inspirationString)
            print("The file doesn't exist.")

        }

它在控制台中打印出来:

/var/mobile/Containers/Data/Application/42E96A6F-D16C-4AB4-84FC-315109AC3374/Documents/sound.caf

该文件不存在。

1 个答案:

答案 0 :(得分:0)

试试这段代码,它对我有用:

if audioRecorder?.recording == false {

    let inspirationString = inspirations[indexPath.row].valueForKey("fileDirectory") as! String
    let fileDirString = NSURL(fileURLWithPath: inspirationString)!

    if !NSFileManager.defaultManager().fileExistsAtPath(inspirationString) {

        print(inspirationString)
        print("The file doesn't exist.")

    }
}

基本上,NSURL(fileURLWithPath: inspirationString)!适用于本地文件而不是NSURL(string: inspirationString)!