I am building a simple calculator project in Java using Swing and I want to play a sound when the user clicks on the buttons in the app. I don't know how to achieve this.
Asked
Active
Viewed 41 times
-2
-
1Please provide enough code so others can better understand or reproduce the problem. – Community Jul 12 '22 at 07:45
-
The Oracle tutorial [Sound](https://docs.oracle.com/javase/tutorial/sound/index.html) might help you. Adding sound to a Swing application is not a simple process. You don't want to block the [Event Dispatch Thread](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) playing sound. – Gilbert Le Blanc Jul 12 '22 at 11:32
-
1See: https://stackoverflow.com/questions/64509691/how-can-i-add-some-sound-to-my-java-jframe/64509714#64509714 for a simple example. – camickr Jul 12 '22 at 13:40
-
This [example](https://stackoverflow.com/a/17767350/230513) illustrates using `javax.sound.midi`. If this is not a duplicate, please [edit] your question to include a [mre] that shows your revised approach. – trashgod Jul 12 '22 at 17:36
1 Answers
0
All you need to do is implement an OnTouchListener
on the button and use the AudioManager.playSoundEffect()
public method. Code is shown below:
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
float vol = 0.5; //This will be half of the default system sound
am.playSoundEffect(AudioManager.FX_KEY_CLICK, vol);

Sarmad
- 31
- 4
-
2As far as I am aware, [Swing](https://docs.oracle.com/javase/tutorial/uiswing/) is for desktop applications while `OnTouchListener` is part of Android API and does not exist in Java SE. – Abra Jul 12 '22 at 07:57