I want to my application play random sound when user click on button. So I don't want android natural sound, I want to play my own sound every time user click on one button. Does anyone knows the solution of this problem.
Asked
Active
Viewed 3,277 times
2 Answers
7
To play a sound:
Play sound on button click android
For a random sound you just need to add all sounds in a list. And in the onClickListener just get a random sound from your list. Something like this:
List<Integer> soundList = new ArrayList<Integer>();
soundList.add(R.raw.sound1);
soundList.add(R.raw.sound2);
soundList.add(R.raw.sound3);
soundList.add(R.raw.sound4);
myButton.setOnClickListener(new OnClickListener {
@Override
public void onClick(View v) {
playRandomSound();
}
});
private void playRandomSound() {
int randomInt = (new Random().nextInt(soundList.size()));
int sound = soundList.get(randomInt);
MediaPlayer mp = MediaPlayer.create(this, sound);
mp.start();
}
No guarantee that this works! It's just an example, how you could do it!

Community
- 1
- 1

user3621165
- 212
- 4
- 16
-
Is there a way to disable natural sound of android click – marko kurt Feb 19 '15 at 20:04
-
is there any way to have it play all the songs randomly without halting the main activity? – Zypps987 Nov 18 '16 at 07:33
-
What do you mean? Playing all songs by default in a loop? – user3621165 Nov 18 '16 at 09:46
1
One way to achieve that is:
- Embed your sound , as an MP3 encoded file
Attaching a click event handler in the Android App
myButtonTwo.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) { //code that runs when button is clicked } });
Access and play the embedded MP3 file from the application in the event handler
MediaPlayer mPlayer = MediaPlayer.create(FakeCallScreen.this, R.raw.mysoundfile); mPlayer.start();
see How do I play an mp3 in the res/raw folder of my android app?
A tutorial explaining a complete process
Edit:
To disable native android click sound
yourbutton.setSoundEffectsEnabled(false);
-
I know how to play a sound, but is there a way to disable natural sound of click in android – marko kurt Feb 19 '15 at 20:04
-
see updated answer, google query used : "android api disable click sound" – Alex Feb 22 '15 at 09:33