ios - 快速从文件中读取数据

标签 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) 那么它就可以正常工作。

我已经尝试了一切。但没有任何效果。请让我知道我的代码有什么问题。

最佳答案

  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()
        })
    }

文件资源管理器中添加该视频

然后尝试上面的代码

关于ios - 快速从文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50002104/

相关文章:

ios - 有没有办法将多个 Apple 开发者帐户与单个 iTunes Connect 帐户关联?

objective-c - NSManagedObject 键存在于实体描述中,但当尝试访问它时,应用程序崩溃并显示 "this class is not key value coding-compliant"

ios - 属性字符串下划线不适用于外部字体

objective-c - Swift 中的设置边界

ios - 核心数据关系多对一

ios - AVAudioPlayer initWithData 返回零

ios - 使 UITableView 部分标题与该部分的第一个单元格重叠

ios - 适用于 iOS 的 GraphQL 客户端库

iphone - 在 iPhone 应用程序中播放音频

macos - OS X播放音频帧是否已发送给我