下载音频并在AVAudioPlayer中播放

时间:2019-02-01 10:30:03

标签: swift

我需要下载音频文件,然后播放他。我编写了用于下载的代码,但是我不知道如何将他转移到AVAudioPlayer。

@IBAction func downloadButton(_ sender: Any) {
    if let audioUrl = URL(string: "https://www.dropbox.com/s/qwqxsde1yo5m1mz/Track04.mp3?dl=0") {

        // 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(audioUrl.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 {

            let task = URLSession.shared.downloadTask(with: audioUrl) { (location, response, error) in
                guard let location = location else {return}
                do{
                    try FileManager.default.moveItem(at: location ,to : destinationUrl)
                    print("File moved to documents folder")
                }
                catch {
                    print("error")
                }
            }
            task.resume()

        }

    }

}

@IBAction FUNC playAudio(_发件人:任何){

????????

}

2 个答案:

答案 0 :(得分:0)

使用destintionUrl从documentDirectory获取音乐文件数据,然后将数据分配给播放器对象。

func playSongUsing(_ url : URL) {


do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try AVAudioSession.sharedInstance().setActive(true)

            // For iOS 11 
            objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

            // For iOS versions < 11 
            objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) 

            guard let aPlayer = objPlayer else { return }
            aPlayer.play()

    } catch let error {
            print(error.localizedDescription)
    }


}

答案 1 :(得分:0)

只需使用本地文件url创建AVAudioPlayer实例,如下所示:

if FileManager.default.fileExists(atPath: destinationUrl.path) {
    do {
        self.player = try AVAudioPlayer(contentsOfURL: destinationUrl)
        player.prepareToPlay()
        player.volume = 1
        player.play()
    } catch {
        print(error)
    }
}