在SwiftUI应用中将音频播放代码放置在何处 [英] Where to place code for audio playback in a SwiftUI app
问题描述
在基于SwiftUI的应用中(即没有UIViewController类)将音频播放代码放置在哪里的最佳位置是什么?我要播放的声音是由视图启动的,因此我正在考虑将其放入相应的视图模型类中.但是由于模型类是关于数据的,所以我认为应该有一个更好的选择.最好的架构是什么?
Where is the best place to put code for audio playback in a SwiftUI based app, i.e. not having UIViewController classes? The sound I want to play is initiated by a view, so I'm thinking of putting it into the corresponding view model class. But as a model class is about data, I think there should be a better option. What's the best architecture?
推荐答案
正确,视图不应该处理数据. SwiftUI会强制执行此逻辑.
Correct, the View shouldn't take care of data. And SwiftUI enforces this logic.
您可以创建一个播放器类,该类负责播放音频.并将其添加为EnvironmentObject
,以便您可以通过View
中的按钮进行控制.然后,您可以做一些有趣的事情,例如绑定播放按钮,以根据播放器是否正在播放:)
You could create a Player class which takes care of playing the audio. And add it as an EnvironmentObject
, so you can control it with your button in the View
. You can then do sweet things like binding your play button to show different images depending on whether the player is... playing :)
更新
Xcode 11 beta 4的代码已更新(用willChange
代替didChange
)
Update
Code has been updated for Xcode 11 beta 4 (willChange
instead of didChange
)
struct PlayerView : View {
@EnvironmentObject private var player: Player
var body: some View {
Button(action: {
self.player.pauseOrPlay()
}) {
Image(systemName: player.isPlaying ? "pause.circle.fill" : "play.circle.fill").font(.title).frame(minWidth: 44, minHeight: 44)
}
}
}
class Player: BindableObject {
let willChange = PassthroughSubject<Player, Never>()
var isPlaying: Bool = false {
willSet {
willChange.send(self)
}
}
func pauseOrPlay() {
// Code that toggles the audio on and off
}
}
这篇关于在SwiftUI应用中将音频播放代码放置在何处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!