gpt4 book ai didi

ios - 在swiftui中按钮的触摸 Action 播放音频

转载 作者:行者123 更新时间:2023-12-01 21:27:28 25 4
gpt4 key购买 nike

我想在按下按钮时(一旦单击它)而不是在 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

最佳答案

这是一个可能的方法的演示。使用 Xcode 11.4/iOS 13.4 测试
注意:您应该继续引用 AVAudioPlayer当它正在播放并更好地跟踪它的状态时,所以这更适合在一些帮助类(如 View 模型)中执行

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

关于ios - 在swiftui中按钮的触摸 Action 播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63322997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com