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

标签 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保存到core data中,因为我不能把url保存到core data所以文件路径用string代替:

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

记录器肯定已经创建了一个文件,因为它显示在 TableView 中。但是它不能播放,所以我检查了文件是否存在于提供的文件路径中:

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

文件不存在。

最佳答案

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

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)!

关于ios - 尝试播放录制的文件时文件路径不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31936752/

相关文章:

ios - Swift : How $0 works in Array. forEach?

ios - 将其他 UI 元素添加到 UITableViewCells

ios - 我可以通过编码在核心数据中创建和删除实体吗

android - 由于缺少 info.plist 和其他文件,Worklight 在 OS X、iPhone 和 Android 上的构建失败

ios - 每 5 秒递增 NSnumber - Cocos2d

ios - 单击不同按钮时删除按钮上的选定状态(Swift)

swift - watch 应用程序 - 当文本太长时替换...

objective-c - Objective-C 和 swift

ios - 插入扩展抽象实体的实体时出错

ios - 向用户显示 iCloud 同步正在进行中