我已经尝试了所有可能的订阅方法,但没有收到任何通知
let musicPlayer = MPMusicPlayerController.systemMusicPlayer
let appMusicPlayer = MPMusicPlayerController.applicationMusicPlayer
let queuePlayer = MPMusicPlayerController.applicationQueuePlayer
func subscribe() {
MPMediaLibrary.requestAuthorization { _ in }
musicPlayer.beginGeneratingPlaybackNotifications()
appMusicPlayer.beginGeneratingPlaybackNotifications()
queuePlayer.beginGeneratingPlaybackNotifications()
NotificationCenter.default.addObserver(forName: .MPMusicPlayerControllerPlaybackStateDidChange, object: musicPlayer, queue: .main) { [weak self] notification in
debugPrint("hello")
}
NotificationCenter.default.addObserver(forName: .MPMusicPlayerControllerPlaybackStateDidChange, object: appMusicPlayer, queue: .main) { [weak self] notification in
debugPrint("hello")
}
NotificationCenter.default.addObserver(forName: .MPMusicPlayerControllerPlaybackStateDidChange, object: queuePlayer, queue: .main) { [weak self] notification in
debugPrint("hello")
}
NotificationCenter.default.addObserver(
self,
selector: #selector(playbackStateChanged(_:)),
name: .MPMusicPlayerControllerPlaybackStateDidChange,
object: musicPlayer
)
NotificationCenter.default.addObserver(
self,
selector: #selector(playbackStateChanged(_:)),
name: .MPMusicPlayerControllerPlaybackStateDidChange,
object: appMusicPlayer
)
NotificationCenter.default.addObserver(
self,
selector: #selector(playbackStateChanged(_:)),
name: .MPMusicPlayerControllerPlaybackStateDidChange,
object: queuePlayer
)
}
将“NSAppleMusicUsageDescription”添加到您的 .plist 文件中并包含字符串值 这描述了为什么您需要访问媒体播放器框架。
使用示例代码
import SwiftUI
import MediaPlayer
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("SetupMusic").onTapGesture {
setup()
}
}
.padding()
}
}
private func setup() {
debugPrint("Rquesting access")
MPMediaLibrary.requestAuthorization { permission in
debugPrint("Setting up music player")
let musicPlayer = MPMusicPlayerController.systemMusicPlayer
musicPlayer.beginGeneratingPlaybackNotifications()
musicPlayer.beginGeneratingPlaybackNotifications()
debugPrint("Intial State: \(musicPlayer.playbackState)")
NotificationCenter.default.addObserver(forName: .MPMusicPlayerControllerPlaybackStateDidChange, object: musicPlayer, queue: .main) { notification in
debugPrint("State changed to \(musicPlayer.playbackState)")
}
}
}
#Preview {
ContentView()
}