Reputation: 2612
How can I play a song using AVPlayer? Here is my code.
let song = filteredMusic[indexPath.row]
let query = MPMediaQuery.songsQuery()
let isPresent = MPMediaPropertyPredicate(value: song, forProperty: MPMediaItemPropertyTitle, comparisonType: .EqualTo)
query.addFilterPredicate(isPresent)
let result = query.items //only going to be one song
if result!.count == 0 {
print("not found")
return
}
let url = result![0].assetURL // for some reason this is nil
let item = AVPlayerItem(URL: url!)
let player = AVPlayer(playerItem: item)
player.play()
The asset url is nil. How come?
Upvotes: 0
Views: 1133
Reputation: 2612
Thanks to NKushwah for the help! I am posting my own answer for a couple reasons.
let song = filteredMusic[indexPath.row]
let query = MPMediaQuery.songsQuery()
let isPresent = MPMediaPropertyPredicate(value: song, forProperty: MPMediaItemPropertyTitle, comparisonType: .EqualTo)
query.addFilterPredicate(isPresent)
let result = query.collections
if result!.count == 0 {
print("not found")
return
}
let controller = MPMusicPlayerController.systemMusicPlayer()
let item = result![0]
controller.setQueueWithItemCollection(item)
controller.prepareToPlay()
controller.play()
}
iPodMusicPlayer
is deprecated! I used systemMusicPlayer
instead.Upvotes: 1
Reputation: 2737
Some MPMediaItelm only have their contents but not URl, So to play these you have to use MPMusicPlayerController-
MPMusicPlayerController *controller = [MPMusicPlayerController iPodMusicPlayer];
MPMediaItem *item = result![0];
[controller setQueueWithItemCollection:collection];
[controller setNowPlayingItem:item];
[controller prepareToPlay];
[controller play];
The applicationMusicPlayer does not support background music. Use MPMusicPlayerController's iPodMusicPlayer
instead. It shares the state with the built-in iPod player and music will continue to play when your app enters the background.
Upvotes: 0