35

How do I set up an audiofile to play when a user touches an image.

Where should I store the audio file and what code should I use to actually play the file? I don't want to bring up the MediaPlayer interface or anything like that.

I was thinking of doing it like this:

foo = (ImageView)this.findViewById(R.id.foo);
    foo.setOnClickListener(this);

public void onClick(View v) {
if (foo.isTouched()) {

 playAudioFile();
  }
}

Thanks

Sachin
  • 2,667
  • 9
  • 35
  • 39
  • 1
    As described in the answer below, put `my_sound.mp3` into `res/raw/` and then reference it via `R.raw.my_sound`. However, then you have two choices: `MediaPlayer` and `SoundPool`. For efficient memory management, you should use a library to work with those classes: https://github.com/delight-im/Android-Audio – caw Apr 01 '15 at 22:41

3 Answers3

70

This won't create a bring up the MediaPlayer interface... it will just play the sound you want.

Button boton = (Button) findViewById(R.id.boton);
boton.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
  MediaPlayer mp = MediaPlayer.create(TestSonido.this, R.raw.slayer);  
  mp.start();
 }
});

In this case, R.raw.slayer represents an audio file called slayer.mp3 that is stored in the res/raw/ folder and once you click the button the droid will rock you...

Cristian
  • 198,401
  • 62
  • 356
  • 264
  • 1
    What will happen if i click button twice before completing previous audio clip , I think then it will play dual audio? – Jay Oct 07 '17 at 10:30
8

You can also achieve the same using SoundPool.

MediaPlayer first loads the whole sound data in memory then play, so it produces some lag when we switch among sounds frequently.

SoundPool is a better option with small size sound file and produces better result with .ogg media file.

SoundPool pl = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        // 5 indicates the maximum number of simultaneous streams for this SoundPool object
pl.setOnLoadCompleteListener(new OnLoadCompleteListener() {             
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                // The onLoadComplet method is called when a sound has completed loading.
                soundPool.play(sampleId, 1f, 1f, 0, 0, 1);
                // second and third parameters indicates left and right value (range = 0.0 to 1.0)
            }
});

Button btn = findViewById(R.id.boton);
btn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

     int sound = pl.load(this, R.raw.sound_01, 0);

 }
});
Aashish Kumar
  • 2,771
  • 3
  • 28
  • 43
0
public void aud_play(View view) {
  if (!mp.isPlaying()) {   //If media player is not playing it.

    mp = MediaPlayer.create(this, R.raw.audio_name);
    mp.start();      

  } else {// Toast of Already playing ...
}
}
Gober
  • 3,632
  • 3
  • 26
  • 33
Rohith S
  • 1
  • 3