SwiftUI 尝试使用 MPMusicPlayerController 和 playbackState

SwiftUI Trying to use MPMusicPlayerController and playbackState

我是 SwiftUI 的新手,我很难使用 Apple Swift 文档。我正在尝试获取正在播放的音乐的当前状态,希望打印出类似

的内容

paused

playing

这是我想出的代码。

import SwiftUI
import MediaPlayer
import AVKit

struct MusicView: View {
        
    @State var playbackState: MPMusicPlaybackState? = MPMusicPlayerController.systemMusicPlayer.playbackState

    @State var updater = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    var body: some View {
        Text("Hello")
            .onAppear(){
                print(playbackState)
            }
            .onReceive(updater){_ in
                playbackState = MPMusicPlayerController.systemMusicPlayer.playbackState
                print(playbackState)
            }
    }
}

我发现它使用起来很混乱,我不明白为什么它一直在打印:

Optional(__C.MPMusicPlaybackState)

我明白为什么它是可选的,但为什么我不能让它打印某种状态?我似乎找到的所有源代码都来自 9 年前的 Obj-C。在这一点上,任何帮助将不胜感激。

Swift 不知道如何将 C 枚举翻译成可打印的文本。您可以使用 switch 语句来打印值。

您也可以监听 NotificationCenter 状态变化的更新,而不是使用 Timer

extension MPMusicPlaybackState {
    func printState() {
        print(self)
        switch self {
        case .interrupted:
            print("interrupted")
        case .stopped:
            print("stopped")
        case .playing:
            print("playing")
        case .paused:
            print("paused")
        case .seekingForward:
            print("seekingForward")
        case .seekingBackward:
            print("seekingBackward")
        @unknown default:
            break
        }
    }
}

struct MusicView: View {
        
    @State var playbackState: MPMusicPlaybackState? = MPMusicPlayerController.systemMusicPlayer.playbackState
    
    var body: some View {
        Text("Hello")
            .onAppear(){
                playbackState?.printState()
            }
            .onReceive(NotificationCenter.default.publisher(for: .MPMusicPlayerControllerPlaybackStateDidChange)){ _ in
                playbackState = MPMusicPlayerController.systemMusicPlayer.playbackState
                playbackState?.printState()
            }
    }
}