从媒体播放器中获取随机播放的曲目
Get Shuffled Tracks from Media Player
我想从媒体播放器中获取队列。我相信我无法读取队列(这是正确的吗?)并且我只能在设置队列时获取队列,例如当我 select 播放某个播放列表时。但是我正在努力获得随机队列。
let musicPlayerController = MPMusicPlayerController.systemMusicPlayer
let myMediaQuery = MPMediaQuery.songs()
let predicateFilter = MPMediaPropertyPredicate(value: chosenPlaylist, forProperty: MPMediaPlaylistPropertyName)
myMediaQuery.filterPredicates = NSSet(object: predicateFilter) as? Set<MPMediaPredicate>
musicPlayerController.setQueue(with: myMediaQuery)
musicPlayerController.repeatMode = .all
musicPlayerController.shuffleMode = .songs
musicPlayerController.play()
for track in myMediaQuery.items! {
print(track.value(forProperty: MPMediaItemPropertyTitle)!)
} // here I don't get the shuffled order that is going to play, just get the original order of the playlist
我需要随机播放,因为我希望能够显示接下来要播放的内容。
我过去在使用 .shuffleMode
时遇到过问题。改为对集合调用 shuffled()
:
// shuffle
func shufflePlaylist() {
let query = MPMediaQuery.songs()
let predicate = MPMediaPropertyPredicate(value: "Art Conspiracy",
forProperty: MPMediaPlaylistPropertyName,
comparisonType: .equalTo)
query.addFilterPredicate(predicate)
guard let items = query.items else { return }
let collection = MPMediaItemCollection(items: items.shuffled())
player.setQueue(with: collection)
player.prepareToPlay()
player.play()
}
我想从媒体播放器中获取队列。我相信我无法读取队列(这是正确的吗?)并且我只能在设置队列时获取队列,例如当我 select 播放某个播放列表时。但是我正在努力获得随机队列。
let musicPlayerController = MPMusicPlayerController.systemMusicPlayer
let myMediaQuery = MPMediaQuery.songs()
let predicateFilter = MPMediaPropertyPredicate(value: chosenPlaylist, forProperty: MPMediaPlaylistPropertyName)
myMediaQuery.filterPredicates = NSSet(object: predicateFilter) as? Set<MPMediaPredicate>
musicPlayerController.setQueue(with: myMediaQuery)
musicPlayerController.repeatMode = .all
musicPlayerController.shuffleMode = .songs
musicPlayerController.play()
for track in myMediaQuery.items! {
print(track.value(forProperty: MPMediaItemPropertyTitle)!)
} // here I don't get the shuffled order that is going to play, just get the original order of the playlist
我需要随机播放,因为我希望能够显示接下来要播放的内容。
我过去在使用 .shuffleMode
时遇到过问题。改为对集合调用 shuffled()
:
// shuffle
func shufflePlaylist() {
let query = MPMediaQuery.songs()
let predicate = MPMediaPropertyPredicate(value: "Art Conspiracy",
forProperty: MPMediaPlaylistPropertyName,
comparisonType: .equalTo)
query.addFilterPredicate(predicate)
guard let items = query.items else { return }
let collection = MPMediaItemCollection(items: items.shuffled())
player.setQueue(with: collection)
player.prepareToPlay()
player.play()
}