I'm trying to play mp3 from Data file I downloaded with Alamofire. The song is fine, I can play it with AVAudioPlayer(data: Data). How should I play the same Data file with AVPlayer? I could not find how to create PlayerItem from Data or AVAsset from Data. Also, I've the url for the song path, but that URL does not work with AVPlayer somehow. Music is just not playing.
func startSong(withIndex: Int) {
if let item = getItem(atIndex: withIndex) {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
let playerItem = item
self.player = AVPlayer(playerItem: playerItem)
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
func getItem(atIndex: Int) -> AVPlayerItem? {
var item: AVPlayerItem
var url: URL
let song = playlist.getSong(index: atIndex)
if PlaylistsService.sharedService.isFileDownloaded(inPath: SongPath.Offline(id: (song?.getID())!).path()) {
url = URL(fileURLWithPath: SongPath.Offline(id: (song?.getID())!).path())
} else if PlaylistsService.sharedService.isFileDownloaded(inPath: SongPath.Temp(id: (song?.getID())!).path()) {
url = URL(fileURLWithPath: SongPath.Temp(id: (song?.getID())!).path())
} else {
self.downloadSong(song: song!)
url = URL(fileURLWithPath: SongPath.Temp(id: (song?.getID())!).path())
}
item = AVPlayerItem(url: url)
return item
}
@IBAction func playPause(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
print("Play")
self.player.play()
} else {
print("Pause")
self.player.pause()
}
}
self.player.play()
. Does that line actually execute? – mattself.player.play()
, you could try logging some further info about the state of the player. What is itscurrentTime
? What is itscurrentItem
? If it has an item, what is that item'sstatus
? What is that item'sasset
? – mattstatus
, log instead thestatus.rawValue
. That will give us a value in the console that we can actually read. We really would like to know if there's astatus
issue with this thing. – matt