Important: make mMediaPlayer
a field, because otherwise the garbage collector will clean up the mediaplayer while the sound is still playing, causing it to be cut off!
private MediaPlayer mMediaPlayer;
private void playSound(int res) {
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
if (am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
mMediaPlayer = MediaPlayer.create(this, res);
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
// Note: onPreparedListener and prepareAsync not needed
// because MediaPlayer.create already takes care of this.
mMediaPlayer.start();
}
}