2

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.

marko kurt
  • 205
  • 4
  • 12

2 Answers2

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
1

One way to achieve that is:

  1. Embed your sound , as an MP3 encoded file
  2. 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
    
        }
    });
    
  3. 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

http://www.accelerated-ideas.com/news/android-app-development--how-to-add-and-play-music-and-audio-files.aspx

Edit:

To disable native android click sound

yourbutton.setSoundEffectsEnabled(false);

source : Disable Button click sound in android

Community
  • 1
  • 1
Alex
  • 768
  • 1
  • 5
  • 13