0

I'm building a list view soundboard and I need a code for play a sound when I click on a item and stop it when another is clicked, then start the new sound. I have tried many code but the app crashes.

user3437592
  • 59
  • 3
  • 9

2 Answers2

1
private MediaPlayer mMediaPlayer = null;

Call playAudio() when an item clicked. it will stop the previous playing audio and play the new.

public void playAudio(int audioId)
{
    // stop the previous playing audio
    if(mMediaPlayer != null && mMediaPlayer.isPlaying())
    {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    mMediaPlayer = MediaPlayer.create(this, audioId);
    mMediaPlayer.start();
}

call this method on item click

 playAudio(R.raw.sound); // change this sound depends on your item
Libin
  • 16,967
  • 7
  • 61
  • 83
0

Put your media file in your raw folder and then

 MediaPlayer song = MediaPlayer.create(this, R.raw.song1);

and when you click on an item in your listView

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
     super.onListItemClick(l, v, position, id);
     song.release();
     song = MediaPlayer.create(this, R.raw.song2);
     song.start();
}
wael
  • 444
  • 4
  • 11