Ios 如何播放应用程序中下载的音频文件?

Ios 如何播放应用程序中下载的音频文件?,ios,swift,audio,Ios,Swift,Audio,我想知道如何播放应用程序中下载的文件,我下载了一个音乐文件,然后我想在应用程序中播放它,我找到了这个函数并使用它下载。 谢谢 func downloadSong (_ sender:UIButton) { if let url = URL(string: startURL) { // then lets create your document folder url let documentsDirectoryURL = FileManager.defa

我想知道如何播放应用程序中下载的文件,我下载了一个音乐文件,然后我想在应用程序中播放它,我找到了这个函数并使用它下载。 谢谢

func downloadSong (_ sender:UIButton) {
    if let url = URL(string: startURL) {
        // then lets create your document folder url
        let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        // lets create your destination file url
        let destinationUrl = documentsDirectoryURL.appendingPathComponent(url.lastPathComponent)
        print(destinationUrl)

        // to check if it exists before downloading it
        if FileManager.default.fileExists(atPath: destinationUrl.path) {
            print("The file already exists at path")

            // if the file doesn't exist
        } else {
            print("Downloading started")

            // you can use NSURLSession.sharedSession to download the data asynchronously
            URLSession.shared.downloadTask(with: url, completionHandler: { (location, response, error) -> Void in
                guard let location = location, error == nil else { return }
                print("Downloading finished")

                do {
                    // after downloading your file you need to move it to your destination url
                    try FileManager.default.moveItem(at: location, to: destinationUrl)
                    print("File moved to documents folder")
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }).resume()
        }
    }
}

用你的目标来尝试一款音频播放器

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:destinationUrl error:nil];
player.numberOfLoops = -1; 
[player play];
Swift版本:

let player = try? AVAudioPlayer(contentsOf: destinationUrl)
player?.numberOfLoops = -1;
player?.play()