MediaPlayer release issue - AudioStream issue

I am trying to provide a custom beep when I receive a message in my application. This beep should take into account the notification volume of the main phone (not the ringer volume). This means that if a telephone notification vol = 3/10, then the sound intensity should be 3/10. I cannot achieve this,

  AudioManager audioMan = (AudioManager) context
    int volume;

    if (mPlayer == null) {
        mPlayer = MediaPlayer.create(context, R.raw.mytone);

    if (mPlayer.isPlaying()) {
        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() {
        public boolean onError(MediaPlayer player, int what, int extra) {
            return true;

    if (mVibrator == null)
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);



Could you please share your knowledge and give me directions. Thank.


source to share

1 answer

It looks like you are playing your sound on the music stream coming from the link AudioManager.STREAM_MUSIC

. Changing the volume level changes the level for everything playing in that stream. This is why music / media playback is "crumpled".

If you want to use the call flow (and its volume setting) you must use AudioManager.STREAM_RING

. You say you've tried this, but the piece of code you provided just adjusts the volume - you didn't show how you build and tweak yours MediaPlayer

before asking it to play sound.

When configuring an instance, MediaPlayer

you must select the appropriate stream. Since I have successfully used different threads in the described scenario, this is where your problem lies. To select the audio stream that plays your custom sound, use setAudioStream

in your instance MediaPlayer

as follows:

// 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

// Now play the sound


It is a good practice to offer your users the ability to choose a stream for themselves - in addition to music and call streams, there are alarm and notification streams, each with an independent volume level (there are others, but this is the core). Take a look at the Android documentation on AudioManager here .



All Articles