Android Boy
Android Boy

Reputation: 4345

How to Control the audio volume which is playing from Service?

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.

Upvotes: 5

Views: 718

Answers (2)

M_M
M_M

Reputation: 136

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.

Upvotes: 1

Fred Felsbruckner
Fred Felsbruckner

Reputation: 88

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);

Upvotes: 3

Related Questions