Wednesday, January 19, 2011

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) {
}

1 comment:

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

    ReplyDelete

Androidians