Reputation: 8433
I am trying to provide a custom beep sound when I get a message in my Application. This beep sound should respect the master phone notification volume level(not ringer volume). Which means if phone notification vol =3/10 , then beep intensity should be 3/10. I am not able to achieve this,
AudioManager audioMan = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
int volume;
if (mPlayer == null) {
mPlayer = MediaPlayer.create(context, R.raw.mytone);
}
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.release();
mPlayer = MediaPlayer.create(context, R.raw.mytone);
}
volume = audioMan.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
mPlayer.setVolume(volume, volume);//this doesn't work for me, beep sound is taking media player volume by default.
mPlayer.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer player, int what, int extra) {
player.stop();
player.reset();
return true;
}
});
if (mVibrator == null)
mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
mVibrator.cancel();
Can you please share your knowledge and give me directions. Thank you.
Upvotes: 3
Views: 1223
Reputation: 4591
It looks like you are playing your sound over the music stream going by the reference to AudioManager.STREAM_MUSIC
. Modifying the volume level modifies the level for everything played on that stream. This is why music/media playback is 'mucked up'.
If you want to use the ringer stream (and its volume setting) then you should be using AudioManager.STREAM_RING
instead. You say you've tried this but the code snippet you've given just adjusts the volume - you've not shown how you create and configure your MediaPlayer
before you ask it to play your sound.
You've got to select the appropriate stream when you set up your MediaPlayer
instance. As I've successfully used different streams in the kind of scenario you are describing, this is where your problem lies. To select the audio stream over which your custom beep is played, use setAudioStream
on your MediaPlayer
instance like this:
// Get a reference to the MP3 file to play
AssetFileDescriptor afd = getContext().getResources().openRawResourceFd(R.raw.my_mp3);
// Create the media player
MediaPlayer mediaPlayer = new MediaPlayer();
// Give it the MP3 you want played
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
// Set the audio stream to play over
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
// Now play the sound
mediaPlayer.prepare();
mediaPlayer.start();
Its good practice to offer your users the option to choose the stream for themselves - in addition to the music and ringer streams there are alarm and notification streams, each with an independent volume level (there are others too, but these are the core ones). Have a look at the Android documentation on AudioManager here.
Upvotes: 4