Reputation: 59
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.
Upvotes: 0
Views: 1757
Reputation: 17085
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
Upvotes: 1
Reputation: 454
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();
}
Upvotes: 0