5

My apps playing two audio, first from service and second from activity. I want to decrease the volume of first audio when second audio is playing. After stop the second audio, the volume of first audio should be increases.

2
  • Which Apis are you using for playback? Aug 28, 2015 at 6:02
  • Using Android MediaPlayer and audio is in my raw folder. Aug 28, 2015 at 6:10

2 Answers 2

3

MediaPlayer has methods for that. It sets volume for left and right channel. Unmuted:

mediaPlayerA.setVolume(1.0f, 1.0f);

mute the other player

mediaPlayerB.setVolume(0.0f, 0.0f);
1
  • Simple but helpful. Thanks ;.)
    – JanPl
    Nov 23, 2015 at 21:51
1

Not sure how you implemented your MediaPlayer to coincide with your service, but in my test, I created an instance of MediaPlayer within my service class. In order to control the volume of the MediaPlayer instance of the service class, outside of it's service class, I set the MediaPlayer instance as a static member.

So in my service class i did this:

static MediaPlayer mediaPlayer = new MediaPlayer();

In my activity (which has it's own audio playing) I did this:

MyOwnService.mediaPlayer.setVolume(0.1f, 0.1f);

So, when I jumped into my activity, I used this statement first, before playing the activity's audio. Notice I did not mute (0.0f, 0.0f) it. You can play around with your floats until it suits your needs. It ranges between 0.0f - 1.0f.

In my Activity, I also implemented the MediaPlayer.OnCompletionListener, so that I know when the audio for the Activity was complete. This interface has one method to implement, onCompletion(MediaPlayer mp). This method gets called once the audio is complete.

So in my activity I also did this:

@Override
public void onCompletion(MediaPlayer mp) {
    MyOwnService.mediaPlayer.setVolume(1.0f, 1.0f);
}

Here, I then raised the volume of the service music back to max, since the audio playback within it's activity has now completed.

Again, this was all in test, and I wouldn't like to expose a static member just like that (in a published app), I would encapsulate it some how, so there's some type of access control.

I hope this was helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.