上次简单地介绍了AudioRecord和AudioTrack的使用,这次就结合SurfaceView实现一个Android版的手机模拟信号示波器。最近物联网炒得很火,作为手机软件开发者,如何在不修改手机硬件电路的前提下实现与第三方传感器结合呢?麦克风就是一个很好的ADC接口,通过麦克风与第三方传感器结合,再在软件里对模拟信号做相应的处理,就可以提供更丰富的传感化应用。

       先来看看本文程序运行的效果图(屏幕录像速度较慢,真机实际运行起来会更加流畅):

       本文程序使用8000hz的采样率,对X轴方向绘图的实时性要求较高,如果不降低X轴的分辨率,程序的实时性较差,因此程序对X轴数据缩小区间为8倍~16倍。由于采用16位采样,因此Y轴数据的高度相对于手机屏幕来说也偏大,程序也对Y轴数据做缩小,区间为1倍~10倍。在SurfaceView的OnTouchListener方法里加入了波形基线的位置调节,直接在SurfaceView控件上触摸即可控制整体波形偏上或偏下显示。

       main.xml源码如下:

XML/HTML代码
  1. <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"   
  2.         android:orientation="vertical" android:layout_width="fill_parent"  
  3.         android:layout_height="fill_parent">  
  4.         <linearlayout android:id="@+id/LinearLayout01"   
  5.                 android:layout_height="wrap_content" android:layout_width="fill_parent"  
  6.                 android:orientation="horizontal">  
  7.                 <button android:layout_height="wrap_content" android:id="@+id/btnStart"   
  8.                         android:text="开始" android:layout_width="80dip">  
  9.                 <button android:layout_height="wrap_content" android:text="停止"   
  10.                         android:id="@+id/btnExit" android:layout_width="80dip">  
  11.                 <zoomcontrols android:layout_width="wrap_content"   
  12.                         android:layout_height="wrap_content" android:id="@+id/zctlX">  
  13.                 <zoomcontrols android:layout_width="wrap_content"   
  14.                         android:layout_height="wrap_content" android:id="@+id/zctlY">  
  15.           
  16.         <surfaceview android:id="@+id/SurfaceView01"   
  17.                 android:layout_height="fill_parent" android:layout_width="fill_parent">  

       ClsOscilloscope.java是实现示波器的类库,包含AudioRecord操作线程和SurfaceView绘图线程的实现,两个线程同步操作,代码如下:

Java代码
  1. package com.testOscilloscope;  
  2. import java.util.ArrayList;  
  3. import android.graphics.Canvas;  
  4. import android.graphics.Color;  
  5. import android.graphics.Paint;  
  6. import android.graphics.Rect;  
  7. import android.media.AudioRecord;  
  8. import android.view.SurfaceView;  
  9. public class ClsOscilloscope {  
  10.         private ArrayList inBuf = new ArrayList();  
  11.         private boolean isRecording = false;// 线程控制标记  
  12.         /** 
  13.          * X轴缩小的比例 
  14.          */  
  15.         public int rateX = 4;  
  16.         /** 
  17.          * Y轴缩小的比例 
  18.          */  
  19.         public int rateY = 4;  
  20.         /** 
  21.          * Y轴基线 
  22.          */  
  23.         public int baseLine = 0;  
  24.         /** 
  25.          * 初始化 
  26.          */  
  27.         public void initOscilloscope(int rateX, int rateY, int baseLine) {  
  28.                 this.rateX = rateX;  
  29.                 this.rateY = rateY;  
  30.                 this.baseLine = baseLine;  
  31.         }  
  32.         /** 
  33.          * 开始 
  34.          *  
  35.          * @param recBufSize 
  36.          *            AudioRecord的MinBufferSize 
  37.          */  
  38.         public void Start(AudioRecord audioRecord, int recBufSize, SurfaceView sfv,  
  39.                         Paint mPaint) {  
  40.                 isRecording = true;  
  41.                 new RecordThread(audioRecord, recBufSize).start();// 开始录制线程  
  42.                 new DrawThread(sfv, mPaint).start();// 开始绘制线程  
  43.         }  
  44.         /** 
  45.          * 停止 
  46.          */  
  47.         public void Stop() {  
  48.                 isRecording = false;  
  49.                 inBuf.clear();// 清除  
  50.         }  
  51.         /** 
  52.          * 负责从MIC保存数据到inBuf 
  53.          *  
  54.          * @author GV 
  55.          *  
  56.          */  
  57.         class RecordThread extends Thread {  
  58.                 private int recBufSize;  
  59.                 private AudioRecord audioRecord;  
  60.                 public RecordThread(AudioRecord audioRecord, int recBufSize) {  
  61.                         this.audioRecord = audioRecord;  
  62.                         this.recBufSize = recBufSize;  
  63.                 }  
  64.                 public void run() {  
  65.                         try {  
  66.                                 short[] buffer = new short[recBufSize];  
  67.                                 audioRecord.startRecording();// 开始录制  
  68.                                 while (isRecording) {  
  69.                                         // 从MIC保存数据到缓冲区  
  70.                                         int bufferReadResult = audioRecord.read(buffer, 0,  
  71.                                                         recBufSize);  
  72.                                         short[] tmpBuf = new short[bufferReadResult / rateX];  
  73.                                         for (int i = 0, ii = 0; i < tmpBuf.length; i++, ii = i  
  74.                                                         * rateX) {  
  75.                                                 tmpBuf[i] = buffer[ii];  
  76.                                         }  
  77.                                         synchronized (inBuf) {//  
  78.                                                 inBuf.add(tmpBuf);// 添加数据  
  79.                                         }  
  80.                                 }  
  81.                                 audioRecord.stop();  
  82.                         } catch (Throwable t) {  
  83.                         }  
  84.                 }  
  85.         };  
  86.         /** 
  87.          * 负责绘制inBuf中的数据 
  88.          *  
  89.          * @author GV 
  90.          *  
  91.          */  
  92.         class DrawThread extends Thread {  
  93.                 private int oldX = 0;// 上次绘制的X坐标  
  94.                 private int oldY = 0;// 上次绘制的Y坐标  
  95.                 private SurfaceView sfv;// 画板  
  96.                 private int X_index = 0;// 当前画图所在屏幕X轴的坐标  
  97.                 private Paint mPaint;// 画笔  
  98.                 public DrawThread(SurfaceView sfv, Paint mPaint) {  
  99.                         this.sfv = sfv;  
  100.                         this.mPaint = mPaint;  
  101.                 }  
  102.                 public void run() {  
  103.                         while (isRecording) {  
  104.                                 ArrayList buf = new ArrayList();  
  105.                                 synchronized (inBuf) {  
  106.                                         if (inBuf.size() == 0)  
  107.                                                 continue;  
  108.                                         buf = (ArrayList) inBuf.clone();// 保存  
  109.                                         inBuf.clear();// 清除  
  110.                                 }  
  111.                                 for (int i = 0; i < buf.size(); i++) {  
  112.                                         short[] tmpBuf = buf.get(i);  
  113.                                         SimpleDraw(X_index, tmpBuf, rateY, baseLine);// 把缓冲区数据画出来  
  114.                                         X_index = X_index + tmpBuf.length;  
  115.                                         if (X_index > sfv.getWidth()) {  
  116.                                                 X_index = 0;  
  117.                                         }  
  118.                                 }  
  119.                         }  
  120.                 }  
  121.                 /** 
  122.                  * 绘制指定区域 
  123.                  *  
  124.                  * @param start 
  125.                  *            X轴开始的位置(全屏) 
  126.                  * @param buffer 
  127.                  *            缓冲区 
  128.                  * @param rate 
  129.                  *            Y轴数据缩小的比例 
  130.                  * @param baseLine 
  131.                  *            Y轴基线 
  132.                  */  
  133.                 void SimpleDraw(int start, short[] buffer, int rate, int baseLine) {  
  134.                         if (start == 0)  
  135.                                 oldX = 0;  
  136.                         Canvas canvas = sfv.getHolder().lockCanvas(  
  137.                                         new Rect(start, 0, start + buffer.length, sfv.getHeight()));// 关键:获取画布  
  138.                         canvas.drawColor(Color.BLACK);// 清除背景  
  139.                         int y;  
  140.                         for (int i = 0; i < buffer.length; i++) {// 有多少画多少  
  141.                                 int x = i + start;  
  142.                                 y = buffer[i] / rate + baseLine;// 调节缩小比例,调节基准线  
  143.                                 canvas.drawLine(oldX, oldY, x, y, mPaint);  
  144.                                 oldX = x;  
  145.                                 oldY = y;  
  146.                         }  
  147.                         sfv.getHolder().unlockCanvasAndPost(canvas);// 解锁画布,提交画好的图像  
  148.                 }  
  149.         }  
  150. }  

       testOscilloscope.java是主程序,控制UI和ClsOscilloscope,代码如下:

Java代码
  1. package com.testOscilloscope;  
  2. import android.app.Activity;  
  3. import android.graphics.Color;  
  4. import android.graphics.Paint;  
  5. import android.media.AudioFormat;  
  6. import android.media.AudioRecord;  
  7. import android.media.MediaRecorder;  
  8. import android.os.Bundle;  
  9. import android.view.MotionEvent;  
  10. import android.view.SurfaceView;  
  11. import android.view.View;  
  12. import android.view.View.OnTouchListener;  
  13. import android.widget.Button;  
  14. import android.widget.ZoomControls;  
  15. public class testOscilloscope extends Activity {  
  16.     /** Called when the activity is first created. */  
  17.         Button btnStart,btnExit;  
  18.         SurfaceView sfv;  
  19.     ZoomControls zctlX,zctlY;  
  20.       
  21.     ClsOscilloscope clsOscilloscope=new ClsOscilloscope();  
  22.       
  23.         static final int frequency = 8000;//分辨率  
  24.         static final int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;  
  25.         static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;  
  26.         static final int xMax = 16;//X轴缩小比例最大值,X轴数据量巨大,容易产生刷新延时  
  27.         static final int xMin = 8;//X轴缩小比例最小值  
  28.         static final int yMax = 10;//Y轴缩小比例最大值  
  29.         static final int yMin = 1;//Y轴缩小比例最小值  
  30.           
  31.         int recBufSize;//录音最小buffer大小  
  32.         AudioRecord audioRecord;  
  33.         Paint mPaint;  
  34.     @Override  
  35.     public void onCreate(Bundle savedInstanceState) {  
  36.         super.onCreate(savedInstanceState);  
  37.         setContentView(R.layout.main);  
  38.         //录音组件  
  39.                 recBufSize = AudioRecord.getMinBufferSize(frequency,  
  40.                                 channelConfiguration, audioEncoding);  
  41.                 audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,  
  42.                                 channelConfiguration, audioEncoding, recBufSize);  
  43.                 //按键  
  44.                 btnStart = (Button) this.findViewById(R.id.btnStart);  
  45.                 btnStart.setOnClickListener(new ClickEvent());  
  46.                 btnExit = (Button) this.findViewById(R.id.btnExit);  
  47.                 btnExit.setOnClickListener(new ClickEvent());  
  48.                 //画板和画笔  
  49.                 sfv = (SurfaceView) this.findViewById(R.id.SurfaceView01);   
  50.                 sfv.setOnTouchListener(new TouchEvent());  
  51.         mPaint = new Paint();    
  52.         mPaint.setColor(Color.GREEN);// 画笔为绿色    
  53.         mPaint.setStrokeWidth(1);// 设置画笔粗细   
  54.         //示波器类库  
  55.         clsOscilloscope.initOscilloscope(xMax/2, yMax/2, sfv.getHeight()/2);  
  56.           
  57.         //缩放控件,X轴的数据缩小的比率高些  
  58.                 zctlX = (ZoomControls)this.findViewById(R.id.zctlX);  
  59.                 zctlX.setOnZoomInClickListener(new View.OnClickListener() {  
  60.                         @Override  
  61.                         public void onClick(View v) {  
  62.                                 if(clsOscilloscope.rateX>xMin)  
  63.                                         clsOscilloscope.rateX--;  
  64.                                 setTitle("X轴缩小"+String.valueOf(clsOscilloscope.rateX)+"倍"  
  65.                                                 +","+"Y轴缩小"+String.valueOf(clsOscilloscope.rateY)+"倍");  
  66.                         }  
  67.                 });  
  68.                 zctlX.setOnZoomOutClickListener(new View.OnClickListener() {  
  69.                         @Override  
  70.                         public void onClick(View v) {  
  71.                                 if(clsOscilloscope.rateX<xmax)  
  72.                                         clsOscilloscope.rateX++;          
  73.                                 setTitle("X轴缩小"+String.valueOf(clsOscilloscope.rateX)+"倍"  
  74.                                                 +","+"Y轴缩小"+String.valueOf(clsOscilloscope.rateY)+"倍");  
  75.                         }  
  76.                 });  
  77.                 zctlY = (ZoomControls)this.findViewById(R.id.zctlY);  
  78.                 zctlY.setOnZoomInClickListener(new View.OnClickListener() {  
  79.                         @Override  
  80.                         public void onClick(View v) {  
  81.                                 if(clsOscilloscope.rateY>yMin)  
  82.                                         clsOscilloscope.rateY--;  
  83.                                 setTitle("X轴缩小"+String.valueOf(clsOscilloscope.rateX)+"倍"  
  84.                                                 +","+"Y轴缩小"+String.valueOf(clsOscilloscope.rateY)+"倍");  
  85.                         }  
  86.                 });  
  87.                   
  88.                 zctlY.setOnZoomOutClickListener(new View.OnClickListener() {  
  89.                         @Override  
  90.                         public void onClick(View v) {  
  91.                                 if(clsOscilloscope.rateY<ymax)  
  92.                                         clsOscilloscope.rateY++;          
  93.                                 setTitle("X轴缩小"+String.valueOf(clsOscilloscope.rateX)+"倍"  
  94.                                                 +","+"Y轴缩小"+String.valueOf(clsOscilloscope.rateY)+"倍");  
  95.                         }  
  96.                 });  
  97.     }  
  98.         @Override  
  99.         protected void onDestroy() {  
  100.                 super.onDestroy();  
  101.                 android.os.Process.killProcess(android.os.Process.myPid());  
  102.         }  
  103.           
  104.         /** 
  105.          * 按键事件处理 
  106.          * @author GV 
  107.          * 
  108.          */  
  109.         class ClickEvent implements View.OnClickListener {  
  110.                 @Override  
  111.                 public void onClick(View v) {  
  112.                         if (v == btnStart) {  
  113.                                 clsOscilloscope.baseLine=sfv.getHeight()/2;  
  114.                                 clsOscilloscope.Start(audioRecord,recBufSize,sfv,mPaint);  
  115.                         } else if (v == btnExit) {  
  116.                                 clsOscilloscope.Stop();  
  117.                         }  
  118.                 }  
  119.         }  
  120.         /** 
  121.          * 触摸屏动态设置波形图基线 
  122.          * @author GV 
  123.          * 
  124.          */  
  125.         class TouchEvent implements OnTouchListener{  
  126.                 @Override  
  127.                 public boolean onTouch(View v, MotionEvent event) {  
  128.                         clsOscilloscope.baseLine=(int)event.getY();  
  129.                         return true;  
  130.                 }  
  131.                   
  132.         }  
  133. }  
本文发布:Android开发网
本文地址:http://www.jizhuomi.com/android/course/465.html
2015年8月10日
发布:鸡啄米 分类:Android开发教程 浏览: 评论:0