在swiftui中按钮的触摸动作播放音频
Posted
技术标签:
【中文标题】在swiftui中按钮的触摸动作播放音频【英文标题】:Play audio on touch down action of button in swiftui 【发布时间】:2020-08-09 06:00:57 【问题描述】:我想在按下按钮时播放音频(一旦单击它)而不是 SwiftUI 中的触摸释放。我该如何实现?
我的代码如下所示:
struct PressedButtonStyle: ButtonStyle
let touchDown: () -> ()
func makeBody(configuration: Self.Configuration) -> some View
configuration.label
.foregroundColor(configuration.isPressed ? Color.gray : Color.blue)
.background(configuration.isPressed ? self.handlePressed() : Color.clear)
private func handlePressed() -> Color
touchDown()
return Color.clear
struct DemoPressedButton: View
@State var audioPlayer: AVAudioPlayer!
var body: some View
Button("Demo")
print(">> tap up")
.buttonStyle(PressedButtonStyle
print(">> tap down")
let sound = Bundle.main.path(forResource: "filename", ofType: "wav")
self.audioPlayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!)) // receives warning about changing state while updating view
self.audioPlayer.play() // breaks
)
调用 self.audioPlayer.play() 时代码中断。 自定义着陆代码来自此链接:SwiftUI button action as soon as button is clicked not on click release
【问题讨论】:
【参考方案1】:这是一个可能的方法的演示。使用 Xcode 11.4 / ios 13.4 测试
注意:你应该在它播放时保持对AVAudioPlayer
的引用并更好地跟踪它的状态,所以这更适合在一些帮助类(比如视图模型)中做
class PlayViewModel
private var audioPlayer: AVAudioPlayer!
func play()
let sound = Bundle.main.path(forResource: "filename", ofType: "wav")
self.audioPlayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
self.audioPlayer.play()
struct DemoPressedButton: View
let vm = PlayViewModel()
var body: some View
Button("Demo")
print(">> tap up")
.buttonStyle(PressedButtonStyle
print(">> tap down")
self.vm.play()
)
【讨论】:
看起来有点老套,makeBody
的 ButtonStyle
应该返回静态的东西。预计将在.on...
方法中执行操作。我会谨慎使用这个解决方案。以上是关于在swiftui中按钮的触摸动作播放音频的主要内容,如果未能解决你的问题,请参考以下文章
AVAudioPlayer UIButton - 第二次触摸停止当前音频播放