Reputation: 368
In my android app the user may click on different views to produce piano sounds. My sounds are stored in the raw folder (do_note.mp3,re_note.mp3,...)
My problem is when the user click on a view, a sound is produced but after 6 or 7 clicks the sounds stops and there is no more after. here is my function code :
public int playSound(String tag){
id = context.getResources().getIdentifier(tag, "raw", context.getPackageName());
int soundId = sp.load(context, id,1);
MediaPlayer mPlayer = MediaPlayer.create(context,id);
mPlayer.start();
}
Upvotes: 0
Views: 2306
Reputation: 368
Thank's JakSok
your answer guide me to find solution, in fact i have to call reset and release methods for my MediaPlayer, this is my solution :
if(mPlayer.isPlaying()) {
mPlayer.stop();
}
int id = getResources().getIdentifier(fileName, "raw", getPackageName());
mPlayer.reset();
mPlayer.release();
mPlayer = MediaPlayer.create(this,id);
mPlayer.start();
Upvotes: 1
Reputation: 124
Always check if mPlayer already stopped
@Override
public void onClick(View v) {
if(mPlayer.isPlaying())
{
mPlayer.stop();
mPlayer.reset();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("your.sound");
mPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mPlayer.prepare();
mPlayer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
You can change onClick() method and put code to your function
Hope this helps you
Upvotes: 2