ios - 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。在这一点上,任何帮助将不胜感激。
解决方案
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()
}
}
}
推荐阅读
- sql - 尝试复式记账系统,但获取交易清单是个问题
- r - 使用 ggcorrplot 包更改相关图对角线的方向
- c++ - delete[] (ptr, 0) 的行为
- python - Python,for循环用于打破重复
- highcharts - Highchart-graph 没有出现在 Internet Explorer 中
- neo4j - Neo4j最短路径查询算法的连续关系约束如何表达?
- wordpress - 如何根据填写的结帐页面表格申请折扣
- json - 尝试使用 ruby 和 json 动态填充 infoblox 域名
- postgresql - 如何修复具有多个连接的计数的物化视图?
- terraform - 在嵌套结构的 tfvars 文件中设置变量 terraform 的值