I am creating a alarm kind of application.When I open a particular activity, I want to play a custom sound with alarm volume level of device. If device's media volume is off and alarm volume is on then my custom sound should play.
What have I already tried:
private void playAlarmSound(String fileName) {
MediaPlayer p = new MediaPlayer();
AudioManager audioManager= (AudioManager) getSystemService(AUDIO_SERVICE);
try {
AssetFileDescriptor afd = this.getAssets().openFd(fileName);
int volumeLevel=audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
p.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
p.setVolume(volumeLevel,volumeLevel);
afd.close();
p.prepare();
} catch (Exception e) {
e.printStackTrace();
}
p.start();
}
But by this when media volume is on it is playing sound but when media volume is off it is not playing the sound.
You are reading the alarm volume level but this doesn't mean that the audio will be played through that stream.
You need to build and set the AudioAttributes on the MediaPlayer, indicating USAGE_ALARM.
In other words:
p.setAudioAttributes(
new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
);