我想知道如何播放文件是在应用程序中下载的,我下载了一个音乐文件然后我想在应用程序中播放它,我发现这个功能并用它来下载。 谢谢。
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()
}
}
}
答案 0 :(得分:0)
尝试使用destinationUrl的AVAudioPlayer
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()