0

I'm doing an application with audio files and photos.(dictionary-like) I want to play "A" sound for "A" photo. Sound is played when the button clicked(for to be simple).Application works smoothly BUT the sound does not play when the button clicked too (30-40 clicks). I am sharing my code section.

  ...
  public MediaPlayer mp;
  public Context con;
  public LayoutInflater lf;

  //Sounds and photos
  public Integer[] audios = {
                   R.raw.a, 
                   R.raw.b, 
                   R.raw.c, 
                   R.raw.d  };

  public Integer[] cards = {
                   R.drawable.a, 
                   R.drawable.b, 
                   R.drawable.c, 
                   R.drawable.d };

 public Object instantiateItem(@NonNull ViewGroup container, final int position) {       

 lf = (LayoutInflater) con.getSystemService(con.LAYOUT_INFLATER_SERVICE);
 View view = lf.inflate(R.layout.slide_layout,container,false);
 ImageView imageView = (ImageView) view.findViewById(R.id.imageView);

 ImageButton btn;
 btn=(ImageButton) view.findViewById(R.id.imageButton);
 btn.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

         mp = MediaPlayer.create(con,audios[position]);
         mp.start();
     }
    });

    imageView.setImageResource(cards[position]);
    ViewPager vp = (ViewPager) container;
    vp.addView(view,0);

    return view;
}
...
Mehmet
  • 3
  • 4

1 Answers1

0

Do not create a new MediaPlayer for each sound you play. Create one, and reuse it for each time you want to play a sound.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Can you more explain that? – Mehmet May 01 '19 at 13:09
  • You're calling MediaPlayer.create on each click. You shouldn't do that- MediaPlayer is a heavyweight class, and too many instances cause problems. You should have only one instance of it per Activity, and just tell it to play different songs by reseting it and calling setDataSource – Gabe Sechan May 01 '19 at 13:15