问题
I'm trying to download mp3 file with Alamofire and save it to desired location. Then, from that location, I'm trying to play that file, but it gives me an error.
This is download function
func downloadSong(song: Song, completion: @escaping(Bool) -> ()) {
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: Constants.authName, password: Constants.authKey) {
headers[authorizationHeader.key] = authorizationHeader.value
}
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent("\(song.getID()).mp3")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(APIEndpoint.Song(id: song.getID(), token: self.authToken!).path(), method: .get, headers: headers, to: destination).response { (response) in
if response.error == nil, let filePath = response.destinationURL?.path {
print(filePath)
completion(true)
} else {
completion(false)
}
}
}
This is a playback function
func playSong() {
guard let songs = currentPlaylist?.getSongs() else { return }
let song = songs[0]
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsDirectoryURL.appendingPathComponent("\(song.getID()).mp3")
print(destinationUrl)
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("The file already exists at path")
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player! = try AVAudioPlayer(contentsOf: destinationUrl, fileTypeHint: AVFileTypeMPEGLayer3)
player!.play()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
}
}
I would like to know the best practice of downloading the file and saving it and then playing it.
回答1:
I found out, that I've entered the wrong API url, so it gave me invalid file which is not playable.
EDIT:
The file from the backend was not a valid MP3 audio file, that's why the error occurred.
来源:https://stackoverflow.com/questions/40389522/osstatus-error-1685348671-avaudioplayer