I would like to make a button play a beep sound to indicate it has been pressed. I want to know how to use the default android beep sound (like when you adjust the ringer volume), instead of importing my own mp3 music file or using ToneGenerator?
public void playSound(Context context) throws IllegalArgumentException,
SecurityException,
IllegalStateException,
IOException {
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(context, soundUri);
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
// Uncomment the following line if you aim to play it repeatedly
// mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
}
I found another answer:
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
credit goes to https://stackoverflow.com/a/9622040/737925