从文件swift中读取数据

时间:2018-04-24 12:47:35

标签: ios swift avaudioplayer

我试图读取文件xyz.m4a并试图播放它。但我有一个错误

2018-04-24 18:11:20.010927+0530 Demo[10807:690526] NSURLConnection finished with error - code -1002
2018-04-24 18:11:20.327008+0530 Demo[10807:688427] CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme
Error: The file “xyz.m4a” couldn’t be opened.

这是我的代码:

    func audioMethod() {
    let fileName = "xyz.m4a",
    audioFile = getDocumentsURL().appendingPathComponent(fileName)
    if !FileManager.default.fileExists(atPath: audioFile.path) {
        print("We have no file !!!!!")
    }
    do {
        let audioData = try Data(contentsOf: audioFile)
        if audioPlayer == nil {
            audioPlayer = try AVAudioPlayer.init(data: audioData, fileTypeHint: "m4a")
        }
        audioPlayer?.play()
    } catch let error {
        print("Error: " + error.localizedDescription)
    }
}

func getDocumentsURL() -> URL {
    let urlStr = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
    let url = URL(string: urlStr!)
    return url!
}

如果我将URL直接传递到AVAudioPlayer作为AVAudioPlayer.init(contentsOf: audioFile),那么它可以正常工作。

我已经尝试了一切。但没有任何作用。请告诉我我的代码有什么问题。

1 个答案:

答案 0 :(得分:0)

WorkManager wm = serviceLocator.getWorkManager("NameOfCustomWorkManager");            
AsynchScope scope = wm.findAsynchScope("scopeName");

if (scope == null) 
    scope = wm.createAsynchScope("scopeName");

AlarmManager alarmManager = scope.getAlarmManager();        

alarmManager.create(listener, "Alarm Context Info", (int) (DateUtils.getNextTime(nextTime) - System.currentTimeMillis()));  --Fired on a certain hours     

logger.info("Alarm fired.");

文件资源管理器

中添加该视频

然后尝试上面的代码