How do I get the current volume/amplitude in a MediaPlayer?
You are in luck. There is a class called Visualizer which will do what you want I think.
import android.app.Activity;
import android.media.audiofx.Visualizer;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
private Visualizer audioOutput = null;
public float intensity = 0; //intensity is a value between 0 and 1. The intensity in this case is the system output volume
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createVisualizer();
}
private void createVisualizer(){
int rate = Visualizer.getMaxCaptureRate();
audioOutput = new Visualizer(0); // get output audio stream
audioOutput.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
@Override
public void onWaveFormDataCapture(Visualizer visualizer, byte[] waveform, int samplingRate) {
intensity = ((float) waveform[0] + 128f) / 256;
Log.d("vis", String.valueOf(intensity));
}
@Override
public void onFftDataCapture(Visualizer visualizer, byte[] fft, int samplingRate) {
}
},rate , true, false); // waveform not freq data
Log.d("rate", String.valueOf(Visualizer.getMaxCaptureRate()));
audioOutput.setEnabled(true);
}
}
you will need these permissions:
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"></uses-permission>
You can get the current volume of media player with the help of Audiomanager class.The code is as follows:-
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
int volume_level= am.getStreamVolume(AudioManager.STREAM_MUSIC);
Similarly,if you want to set the default volume of media player.You can do that like as:-
am.setStreamVolume(
AudioManager.STREAM_MUSIC,
volume_level,
0);
That's all..Happy coding :)