How to create a circuit for this signal? Transistor?
You haven't told us much about the nature of the button (number of poles, number of throws), but if a Single Pole, Double Throw (SPDT) button is being used, here's one way you could get that effect.



simulate this circuit &ndash; Schematic created using CircuitLab
But it sounds like you are trying to replace that effective circuit with an equivalent implementation that listens to the button state and outputs either 3.3V or a 250Hz 0-4.5V square wave.
One way to get that effect would be to use an 2-to-1 analog multiplexer, plugin 3.3V into one of its inputs, and plug in the output of a circuit that generates the square 0-4.5V square wave constantly, then use your ESP32 to set the control bits to the analog multiplexer to output the correct input channel based on the state of the button, which you are also tracking with the ESP32.
Assuming you have a 4.5V source voltage, the following circuit will convert a 0-3.3V square wave into a 0-4.5V square wave.



simulate this circuit
Obviously, this requires you to decouple the button from the current circuit and treat it as a &quot;dumb&quot; input to your microcontroller, then disconnect the node which generates the output you measured with your scope and instead connect that node to the output of the analog multiplexer.