How to play ringtone/alarm/notification sound in Android

Playing the default notification sound of the device is the most effective way to notify a user. This can be established by getting the Uri of the audio file from RingtoneManager. To play default alarm tone , ringtone or notification sound from an android app, the following code snippet is useful.

Play Notification Tone

try {
 Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
 Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
 r.play();
 } catch (Exception e) {
 e.printStackTrace();
 }

Play Alarm Tone

To play an Alarm-tone change TYPE_NOTIFICATION to TYPE_ALARM.

try {
 Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
 Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
 r.play();
 } catch (Exception e) {
 e.printStackTrace();
 }

Set & Play a Tone from Raw resources folder

To set a file from the raw folder of your app just change the uri to get the desired file from raw resources. If you have included a tone called sownd.mp3 in your raw resources folder, all you have to do is change

 Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

to

  Uri path = Uri.parse("android.resource://"+getPackageName()+"/raw/sound.mp3");

The code should look like this now

try {
  Uri path = Uri.parse("android.resource://"+getPackageName()+"/raw/sound.mp3");
  // The line below will set it as a default ring tone replace
  // RingtoneManager.TYPE_RINGTONE with RingtoneManager.TYPE_NOTIFICATION
  // to set it as a notification tone
  RingtoneManager.setActualDefaultRingtoneUri(
                    getApplicationContext(), RingtoneManager.TYPE_RINGTONE,
                    path);
  Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), path); 
  r.play();
 } 
catch (Exception e) {
 e.printStackTrace(); 
}