简体   繁体   English

从文件中快速读取数据

[英]Read data from file swift

I was trying to read a file xyz.m4a and trying to play it.我试图读取文件xyz.m4a并尝试播放它。 But I have an error但我有一个错误

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.

Here is my code:这是我的代码:

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

If I pass that URL direct in AVAudioPlayer as AVAudioPlayer.init(contentsOf: audioFile) then it works fine.如果我直接在AVAudioPlayer将该URL作为AVAudioPlayer.init(contentsOf: audioFile)传递,那么它工作正常。

I have tried everything.我已经尝试了一切。 But nothing works.但没有任何作用。 Please let me know what is wrong with my code.请让我知道我的代码有什么问题。

  if let path = Bundle.main.path(forResource: "videoplayback", ofType: "mp4"){
        let video = AVPlayer(url: URL(fileURLWithPath:path))

        let videoPlayer = AVPlayerViewController()
        videoPlayer.player = video
        present(videoPlayer,animated: true,completion: {
            video.play()
        })
    }

Add that Video in File Explorer文件资源管理器中添加该视频

Then try with above code然后尝试使用上面的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM