A little bit ago I found myself needing a android buzzer to play a tone at a set frequency for the android app part of the electrolysis machine I built. I of course googled how to make a buzzer in android and found this wonderful Stack Overflow post here to do it that had a simple implementation.
The implementation there was great but wasn’t exactly out of the box ready so I wrapped it up in a neat little tone player class that runs it in a background thread and has stop and play methods. So I decided to wrap that little class up into it’s own neat little package for other folks to use themselves.
You can grab the project from gradle by adding this to your dependencies:
So there’s a couple ways you can use it, First way is just a continuous buzzer that will continue playing until stop is called.
ContinuousBuzzer tonePlayer = new ContinuousBuzzer(); tonePlayer.play(); Thread.sleep(1000); tonePlayer.stop();
Second way is to play a one time tone sound like so
OneTimeBuzzer buzzer = new OneTimeBuzzer(); buzzer.setDuration(5); buzzer.play();
And the third way is a continuous buzzer that will pause every X seconds for Y seconds long and then keep going, this is useful for cases like mine where I don’t have my eyes on the screen and need to keep track of how long the device has been active for
ContinuousBuzzer tonePlayer = new ContinuousBuzzer(); tonePlayer.setPausePeriodSeconds(5); tonePlayer.setPauseTimeInMs(1000);
You can also set the volume and tone frequency in hz like so. The default frequency is 440hz which I found to be the most pleasant buzzer tone after a dedicated hour or two of fiddling with it (seriously!)
ContinuousBuzzer buzzer = new ContinuousBuzzer(); // volume values are from 0-100 buzzer.setVolume(50); buzzer.setToneFreqInHz(110);
And you can find the source code over on GitHub here.
Thank you for reading my blog!! And check out my other posts if you have the time!