如何从网址下载多个音频文件并在App中离线播放

时间:2018-05-28 06:43:27

标签: ios swift

我想从网址下载多个音频文件,并在App中离线播放。这是我在编码时所做的,但有些时间数组循环停止下载。此外,我还有一个阵列可供下载。这段代码仅供下载。播放音频工作正常。

   override func viewDidLoad() {
    super.viewDidLoad()
    print("Begin of code")
    self.linksToUrls()
    self.startDownloadingUrls()
    print("End of code")
 }
 // create a function to start the audio data download

func getAudioDataFromUrl(audioUrl:NSURL, completion: @escaping ((_ data: NSData?) -> Void)) {
    URLSession.shared.dataTask(with: audioUrl as URL) { (data, response, error) in
        completion(data as NSData?)
        print("dfdgfdg",data!)

        }.resume()
}

// create another function to save the audio data
func saveAudioData(audio:NSData, destination:NSURL) -> Bool {
    if audio.write(to: destination as URL, atomically: true) {
        print("The file \"\(destination.lastPathComponent!)\" was successfully saved.")


        return true
    }
    return false
}

// just convert your links to Urls
func linksToUrls(){
    print("IntroductoryMusicFile1 = count = ",IntroductoryMusicFile1.count)
    audioUrls = NewsAudio1
        .map() { NSURL(string: $0) }
        .filter() { $0 != nil }
    print("introcount",IntroductoryMusicFile1.count)
    musicUrls = IntroductoryMusicFile1


        .map() { NSURL(string: $0) }
        .filter() { $0 != nil }
}



// create a loop to start downloading your urls


func startDownloadingUrls(){
    arrayplay.removeAll()
    //if  (musicUrls = "The URL?"){  }
    //   let syn = SyncBlock()
    for  url in 0 ... musicUrls.count-1 {

        let aaa = musicUrls[url]
        let audioType = audioUrls[url]
        print(aaa!)
        print("audioType",audioType!)


        if aaa == NSURL(string: ""){
            arrayplay.append("")
        }else{
            print("Started downloading \"\(String(describing: aaa?.lastPathComponent!))\".")

            let url1 =  aaa
            let request = URLRequest(url: url1! as URL)
            let task = URLSession.shared.dataTask(with: request) {data, response, error in

                if let httpResponse = response as? HTTPURLResponse {
                    print("statusCode: \(httpResponse.statusCode)")
                    if httpResponse.statusCode == 404{
                        print("Refresh token...")
                        // self.audioPlay()
                        self.arrayplay.append("")
                    }else{


                        self.getAudioDataFromUrl(audioUrl: aaa!) { data in
                            DispatchQueue.main.async() {



                                print("Finished downloading \"\(String(describing: aaa?.lastPathComponent!))\".")
                                print("Started saving \"\(String(describing: aaa?.lastPathComponent!))\".")
                                if self.saveAudioData(audio: data!, destination: self.documentsUrl.appendingPathComponent(aaa!.lastPathComponent!)! as NSURL ) {
                                    // do what ever if writeToURL was successful
                                    //   print("",data)

                                    self.arrayplay.append(aaa!.lastPathComponent!)

                                    self.data1 = self.arrayplay as! [String]
                                    print("data1",self.data1)
                                    print("",self.data1.count)
                                    if self.data1.count == self.musicUrls.count {
                                        print("complete")
                                        self.downloadDataAnnotation()
                                    }
                                    //self.synk.complete()
                                    // print("abc")

                                } else {
                                    //  print("The File \"\(url.lastPathComponent!.stringByDeletingPathExtension)\" was not saved.")
                                }
                            }
                        }



                    }
                }

            }
            task.resume()
        }


    }

}

任何人都可以建议我使用更好的代码或任何其他方式来下载多个音频文件......

0 个答案:

没有答案