Many O gauge sellers have "Battery Eliminators" Basically a buck convertor that is powered through the relay switch. They come with instructions. You need a volt meter to check their output voltage. Some allow you to adjust the output voltage with a small screw on a varistor on the board. Not to be confused with the BCR/BCRL 9v type.
I use them since they don't leak battery acid over time. Adjusting the voltage up a little usually brings many horns back to life.
I have used 9v batteries, but they still can leak and I am probably safer at 2v when my granddaughter runs the train. She likes to hold the horn button until everyone tells her to stop.