我正在使用一个简单的Visualizer类(见下文)来显示MediaPlayer
类的音频输出。但是,这需要android.permission.RECORD_AUDIO
,这似乎吓跑了用户。有没有办法达到相同的结果,但不是android.permission.RECORD_AUDIO
?
展示台代码:
private void setupVisualizerFx() {
int audioSessionId = service.getAudioSessionId();
if (mVisualizer != null) {
mVisualizer.setEnabled(false);
}
mVisualizer = new Visualizer(audioSessionId);
mVisualizer.setEnabled(false);
try {
mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
} catch (IllegalStateException e) {
e.printStackTrace();
}
mVisualizer.setDataCaptureListener(
new Visualizer.OnDataCaptureListener() {
public void onWaveFormDataCapture(Visualizer visualizer,
byte[] bytes, int samplingRate) {
mVisualizerView.updateVisualizer(bytes);
}
public void onFftDataCapture(Visualizer visualizer,
byte[] bytes, int samplingRate) {
}
}, Visualizer.getMaxCaptureRate() / 2, true, false);
}
/**
* A simple class that draws waveform data received from a
* {@link Visualizer.OnDataCaptureListener#onWaveFormDataCapture }
*/
class VisualizerView extends View {
private byte[] mBytes;
private float[] mPoints;
private Rect mRect = new Rect();
private Paint mForePaint = new Paint();
public VisualizerView(Context context) {
super(context);
init();
}
private void init() {
mBytes = null;
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(getContext());
String txtColorString = sharedPref.getString(
PreferencesActivity.KEY_PREF_TXT_COLOR, "");
int txtColor = Integer.parseInt(txtColorString);
mForePaint.setStrokeWidth(1f);
mForePaint.setAntiAlias(true);
mForePaint.setColor(txtColor);
}
public void updateVisualizer(byte[] bytes) {
mBytes = bytes;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBytes == null) {
return;
}
if (mPoints == null || mPoints.length < mBytes.length * 4) {
mPoints = new float[mBytes.length * 4];
}
mRect.set(0, 0, getWidth(), getHeight());
for (int i = 0; i < mBytes.length - 1; i++) {
mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
mPoints[i * 4 + 1] = mRect.height() / 2
+ ((byte) (mBytes[i] + 128)) * (mRect.height() / 2)
/ 128;
mPoints[i * 4 + 2] = mRect.width() * (i + 1)
/ (mBytes.length - 1);
mPoints[i * 4 + 3] = mRect.height() / 2
+ ((byte) (mBytes[i + 1] + 128)) * (mRect.height() / 2)
/ 128;
}
canvas.drawLines(mPoints, mForePaint);
}
}
对Visualizer类的任何其他建议?