How to play ringtone/alarm sound in Android

Federico picture Federico · Apr 11, 2010 · Viewed 214.6k times · Source

I have been looking everywhere how to play a ringtone/alarm sound in Android.

I press a button and I want to play a ringtone/alarm sound. I could not find an easy, straightforward sample. Yes, I already looked at Alarm clock source code... but it is not straightforward and I cannot compile it.

I cannot make this work:

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); 
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(this, alert);
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
    player.setAudioStreamType(AudioManager.STREAM_ALARM);
    player.setLooping(true);
    player.prepare();
    player.start();
}

I get this error:

04-11 17:15:27.638: ERROR/MediaPlayerService(30): Couldn't open fd for
content://settings/system/ringtone

So.. please if somebody knows how to play a default ringtone/alarm let me know.

I prefer not to upload any file. Just play a default ringtone.

Answer

markov00 picture markov00 · Dec 19, 2011

You can simply play a setted ringtone with this:

Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();