Android 实现可视化动态音频柱状图

原文地址:http://www.jb51.net/article/32887.htm


先看一下效果图

 
复制代码 代码如下:

public class FFTActivity extends Activity implements OnClickListener{
private Button button;
private ImageView imageView;
private int frequency = 8000;
private int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
private int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
private RealDoubleFFT transformer;
private int blockSize = 256;
private boolean started = false;
private Canvas canvas;
private Paint paint;
private Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fft);
button = (Button) findViewById(R.id.fft_button);
button.setOnClickListener(this);
imageView = (ImageView) findViewById(R.id.fft_imageView);
transformer = new RealDoubleFFT(blockSize);
bitmap = Bitmap.createBitmap(256, 100, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
}
private class RecordAudio extends AsyncTask<Void, double[], Void> {
@Override
protected Void doInBackground(Void... params) {
int bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC, frequency,
channelConfiguration, audioEncoding, bufferSize);
short[] buffer = new short[blockSize];
double[] toTransform = new double[blockSize];
audioRecord.startRecording();
while (started) {
//将record的数据 读到buffer中,但是我认为叫做write可能会比较合适些。
int bufferResult = audioRecord.read(buffer, 0, blockSize);
for (int i = 0; i < bufferResult; i++) {
toTransform<i> = (double) buffer<i> / Short.MAX_VALUE;
}
transformer.ft(toTransform);
publishProgress(toTransform);
}
audioRecord.stop();
return null;
}
@Override
protected void onProgressUpdate(double[]... values) {
super.onProgressUpdate(values);
canvas.drawColor(Color.BLACK);
for (int i = 0; i < values[0].length; i++) {
int x=i;
int downy=(int)(100-(values[0]<i>)*10);
int upy=100;
canvas.drawLine(x, downy, x, upy, paint);
}
imageView.invalidate();
}
}
@Override
public void onClick(View v) {
started=true;
new RecordAudio().execute();
}
}

android音频可视化的原理是使用离散傅里叶变换,但是数学不好的同学不要担心,有开源的java离散傅里叶变换的代码!!直接到www.netlib.org/fftpack/jfftpack.tgz,直接将里面javasource目录拖动到(ca目录)src即可!!
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值