在swiftui中按按钮的按下动作播放音频

时间:2020-08-09 06:00:57

标签: ios button swiftui

我想在按下按钮时(单击后立即)而不是在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 个答案:

答案 0 :(得分:1)

这里是可能方法的演示。使用Xcode 11.4 / iOS 13.4进行了测试

注意: id code 1 2 E 在播放时应保持引用,并更好地跟踪其状态,因此这在某些辅助类(例如视图模型)中更合适

AVAudioPlayer