Reputation: 820
I am making an Alarm app. I need to play user selected tone which I set through RingtoneManager
.
When an alarm goes off, this is how I play the alarm tone:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Uri alarmSound = prefs.getString("alarmSound", ""); //alarmSound is the Uri of alarm tone
MediaPlayer mp = MediaPlayer.create(NormalAlarm.this, alarmSound);
try
{
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setLooping(true);
mp.start();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
It works fine but the volume which it uses is of course the Media Volume
of the phone. How do I make it work with Alarm Volume
of the phone ?
I am using MediaPlayer
since I want the alarm tone to repeat until the user stops the alarm.
Thanks for your help!
Upvotes: 1
Views: 1373
Reputation: 488
The issue is you are using MediaPlayer.create()
to create your MediaPlayer. Create
function calls the prepare()
function which finalize your media and does not allow you to change AudioStreamType
.
The solution is using setDataSource
instead of create():
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setLooping(true);
try {
mp.setDataSource(NormalAlarm.this, alarmSound);
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
See this link for more information.
Upvotes: 0
Reputation: 4821
MediaPlayer.setAudioStreamType() is what you're looking for:
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setLooping(true);
mp.start();
Upvotes: 3