2017-03-23 4 views
0

Ich möchte wissen, wie ich spielen kann Datei wurde in der App heruntergeladen, ich lade eine Musikdatei, dann möchte ich es in der App spielen, fand ich dieses func und benutze es zum Download. Danke an alle.Wie kann ich Audiodatei abspielen wurde in der App heruntergeladen?

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

Antwort

0

Try AVAudioPlayer mit Ihrem destinationUrl

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

Swift ver:

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