Playing Ringtone in Android

Android have some system ringtones. We can get the uri for these files through RingtoneManager class. Then using AudioManager and mediaplayer, we can play ringTone up on getting some notifications or for alarm etc.

Note : This code won't work on emulator, this will work only on devices. In emulator, we will get IOException

The complete code is,


try {
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) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch(Exception e) {
}

Comments

  1. Thanks! This is exactly what I was looking for!

    ReplyDelete

Post a Comment

Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android