frankish
frankish

Reputation: 6826

How to get volume of AudioTrack in Android?

I can set volume of audioTrack by using track.setStereoVolume(a,b);

But i couldn't find a method to to get the volume, either like getStereoVolume() or setOnVolumeChangedHandler(...)

How can i track the volume level?

Upvotes: 3

Views: 5999

Answers (2)

William Morrison
William Morrison

Reputation: 11006

You can't get the left and right volume levels of an audio track.

So I propose you create an class representing an AudioTrack.

public class AudioPlayer{
    AudioTrack track;
    float leftVolume;
    float rightVolume;
    public AudioPlayer(){
        //create audio track.
        leftVolume = 1;
        rightVolume = 1;
    }
    public void setStereoVolume(float left, float right){
        this.leftVolume = left;
        this.rightVolume = right;
        track.setStereoVolume(left, right);
    }
}

When you're creating your AudioTrack the stereo volume is at 1.0 for both channels. When the volume is set through AudioPlayer it tracks the new level.

This will work, provided AudioTrack is fully encapsulated within AudioPlayer.

Edit:

An AudioTrack has its own volume level independent of other tracks. The stream the AudioTrackis playing on (STREAM_MUSIC, STREAM_SYSTEM etc.) will also influence the final volume level.

So, say your AudioTrack is at .5,.5 for left and right channels, and its playing on STREAM_MUSIC. If that stream is at .5 volume, the final audio level will be

.5*.5 = .25 //for the left and right channels.

If some automatic volume adjustment happens due to power savings or headphones- whatever, it should happen on the Stream level (or somewhere hidden beyond that.) Still, it shouldn't adjust your AudioTrack volume.

Upvotes: 3

Opiatefuchs
Opiatefuchs

Reputation: 9870

Not a real answer, just an assumption: I have not tested it until now, but this should work. I don´t think that You have to override this method. Try it

 AudioManager audioManager = (AudioManager) 
          getSystemService(AUDIO_SERVICE);

      float volume = (float) audioManager.
          getStreamVolume(AudioManager.STREAM_MUSIC);

Upvotes: 1

Related Questions