swiftaudiokit

How to trigger Operation.lineSegment with a button instead of a metronome in AudioKit?


In the AudioKit Cookbook Example "SegmentOperation" there is an "Operation.lineSegment" that creates a linear ramp. It is triggered with a metronome, which in turn is a periodic impulse. How do I create that impulse from the outside world (by clicking a button for example)?

let frequency = Operation.lineSegment(trigger: Operation.metronome(frequency: updateRate),
                                              start: start,
                                              end: 0,
                                              duration: duration)

Thanks in advance.


Solution

  • Solved: Actually we don't need it to be exactly an impulse – any non-zero to zero transition will work. So I've just made a button to toggle the first parameter in the parameters array. This is how I've modified the operation conductor:

    let frequency = Operation.lineSegment(trigger: parameters[0],
                                              start: start,
                                              end: 0,
                                              duration: duration)
    

    And in the View:

    struct ContentView: View {
    @State var lineSeg = true
    var body: some View {
        Button("Toggle: \(lineSeg ? "On" : "Off")") {
            lineSeg.toggle()
            conductor.testEvent.parameter1 = lineSeg ? 1.0 : 0.0
        }
    }