我想知道何时在音乐应用程序上播放歌曲并获取其信息。但是我不想从图书馆中获得所有歌曲,这只是自应用程序开始扫描以来播放的歌曲。
就像您玩某些东西一样,然后打开应用程序,然后扫描您玩的内容。
我已经在搜索此问题,但没有找到任何东西,我不知道从哪里开始实施。
首先,将NSAppleMusicUsageDescription
键添加到Info.plist
中,并描述为什么您需要访问用户的媒体库
然后,您可以找到自一定时间以来与以下代码一起播放的所有歌曲:
import MediaPlayer
@IBAction func getSongs(_ sender: Any) {
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Calendar.current.startOfDay(for: Date()))!
// Check for permissions
switch MPMediaLibrary.authorizationStatus() {
case .authorized, .restricted:
fetchSongPlayed(since: yesterday)
case .notDetermined:
MPMediaLibrary.requestAuthorization { _ in
let auth = MPMediaLibrary.authorizationStatus()
if auth == .authorized || auth == .restricted {
self.fetchSongPlayed(since: yesterday)
}
}
case .denied:
print("No access to the Media Library")
}
}
func fetchSongPlayed(since date: Date) {
let query = MPMediaQuery.songs()
var results = [MPMediaItem]()
if let songs = query.items {
results = songs.filter { ($0.lastPlayedDate ?? Date.distantPast) > date }
} else {
print("Can't fetch songs")
}
// Now do whatever you want with results
// It's an array of MPMediaItem
print(results.count)
}
另一个提示:将一些音乐从iTunes同步到您的设备,因为模拟器没有任何再见默认值。有一种将其添加到模拟器中的方法,但是在设备上测试更容易。