首页 > 解决方案 > SwiftUI尝试使用MPMusicPlayerController和playbackState

问题描述

我对 SwiftUI 还很陌生,并且正在努力使用 Apple Swift 文档。我正在尝试获取正在播放的音乐的当前状态,希望打印类似

暂停

或者

这是我想出的代码。

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)
            }
    }
}

我发现它使用起来非常混乱,而且我不明白为什么它会不断打印:

可选(__C.MPMusicPlaybackState)

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

标签: iosswiftswiftuimpmusicplayercontrollerapple-music

解决方案


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()
            }
    }
}

推荐阅读