问题
There was such a question already, but it seems like the workaround suggested there doesn't work at all. The Visualizer's output is still affected by the global volume and consists of zeroes when the volume is turned all the way down but the MediaPlayer is still playing.
Here's my code to reproduce this issue:
player=new MediaPlayer();
player.setAudioSessionId(SHARED_SESSION_ID);
try {
player.setDataSource("https://example.com/song.mp3");
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
player.prepareAsync();
}catch(Exception x){
Log.w(TAG, x);
}
equalizer=new Equalizer(0, SHARED_SESSION_ID);
equalizer.setEnabled(true);
visualizer=new Visualizer(SHARED_SESSION_ID);
int visualizerFftSize=Visualizer.getCaptureSizeRange()[1];
visualizer.setCaptureSize(visualizerFftSize);
visualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
@Override
public void onWaveFormDataCapture(Visualizer visualizer, byte[] waveform, int samplingRate) {
int max=0, min=255;
for(int i=0;i<waveform.length;i++) {
int w=(int)waveform[i] & 0xFF;
max = Math.max(w, max);
min = Math.min(w, min);
}
Log.i(TAG, "wform "+max+" / "+min);
}
@Override
public void onFftDataCapture(Visualizer visualizer, byte[] fft, int samplingRate) {
int max=0;
for(int i=0;i<fft.length;i++)
max=Math.max((int)fft[i] & 0xFF, max);
Log.i(TAG, "fft max "+max);
}
}, Visualizer.getMaxCaptureRate()/2, true, true);
visualizer.setEnabled(true);
Oddly enough, this example from ApiDemos works just fine on the same devices (Nexus 5, Nexus 4, and Nexus 6P). I tried to copy it as close as possible. I also tried to initialize and/or enable the Equalizer either before or after initializing the Visualizer, but that changed absolutely nothing.
回答1:
I have also met the same problem, thank you for your provide the source code.Just need to set the following code setVolumeControlStream (AudioManager. STREAM_MUSIC);
in your Activity code (such as in onCreate
) and it works for me.
Hope can help you.
来源:https://stackoverflow.com/questions/34467423/visualizer-output-in-android-depends-on-the-device-volume