Android提高第十一篇之模擬信號示波器

本文轉載自:http://blog.csdn.net/hellogv/article/details/6032046

上次簡單地介紹了AudioRecord和AudioTrack的使用,這次就結合SurfaceView實現一個Android版的手機模擬信號示波器(PS:以前也講過J2ME版的手機示波器)。最近物聯網炒得很火作爲手機軟件開發者,如何在不修改手機硬件電路的前提下實現與第三方傳感器結合呢?麥克風就是一個很好的ADC接口,通過麥克風與第三方傳感器結合,再在軟件裏對模擬信號做相應的處理,就可以提供更豐富的傳感化應用。

先來看看本文程序運行的效果圖(屏幕錄像速度較慢,真機實際運行起來會更加流暢):

本文程序使用8000hz的採樣率,對X軸方向繪圖的實時性要求較高,如果不降低X軸的分辨率,程序的實時性較差,因此程序對X軸數據縮小區間爲8倍~16倍。由於採用16位採樣,因此Y軸數據的高度相對於手機屏幕來說也偏大,程序也對Y軸數據做縮小,區間爲1倍~10倍。在SurfaceView的OnTouchListener方法里加入了波形基線的位置調節,直接在SurfaceView控件上觸摸即可控制整體波形偏上或偏下顯示。

main.xml源碼如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical" android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <LinearLayout android:id="@+id/LinearLayout01"
  6. android:layout_height="wrap_content" android:layout_width="fill_parent"
  7. android:orientation="horizontal">
  8. <Button android:layout_height="wrap_content" android:id="@+id/btnStart"
  9. android:text="開始" android:layout_width="80dip"></Button>
  10. <Button android:layout_height="wrap_content" android:text="停止"
  11. android:id="@+id/btnExit" android:layout_width="80dip"></Button>
  12. <ZoomControls android:layout_width="wrap_content"
  13. android:layout_height="wrap_content" android:id="@+id/zctlX"></ZoomControls>
  14. <ZoomControls android:layout_width="wrap_content"
  15. android:layout_height="wrap_content" android:id="@+id/zctlY"></ZoomControls>
  16. </LinearLayout>
  17. <SurfaceView android:id="@+id/SurfaceView01"
  18. android:layout_height="fill_parent" android:layout_width="fill_parent"></SurfaceView>
  19. </LinearLayout>

ClsOscilloscope.java是實現示波器的類庫,包含AudioRecord操作線程和SurfaceView繪圖線程的實現,兩個線程同步操作,代碼如下:

  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<short[]> inBuf = new ArrayList<short[]>();
  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<short[]> buf = new ArrayList<short[]>();
  105. synchronized (inBuf) {
  106. if (inBuf.size() == 0)
  107. continue;
  108. buf = (ArrayList<short[]>) 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,代碼如下:

  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. ClsOscilloscope clsOscilloscope=new ClsOscilloscope();
  21. static final int frequency = 8000;//分辨率
  22. static final int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
  23. static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
  24. static final int xMax = 16;//X軸縮小比例最大值,X軸數據量巨大,容易產生刷新延時
  25. static final int xMin = 8;//X軸縮小比例最小值
  26. static final int yMax = 10;//Y軸縮小比例最大值
  27. static final int yMin = 1;//Y軸縮小比例最小值
  28. int recBufSize;//錄音最小buffer大小
  29. AudioRecord audioRecord;
  30. Paint mPaint;
  31. @Override
  32. public void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.main);
  35. //錄音組件
  36. recBufSize = AudioRecord.getMinBufferSize(frequency,
  37. channelConfiguration, audioEncoding);
  38. audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,
  39. channelConfiguration, audioEncoding, recBufSize);
  40. //按鍵
  41. btnStart = (Button) this.findViewById(R.id.btnStart);
  42. btnStart.setOnClickListener(new ClickEvent());
  43. btnExit = (Button) this.findViewById(R.id.btnExit);
  44. btnExit.setOnClickListener(new ClickEvent());
  45. //畫板和畫筆
  46. sfv = (SurfaceView) this.findViewById(R.id.SurfaceView01);
  47. sfv.setOnTouchListener(new TouchEvent());
  48. mPaint = new Paint();
  49. mPaint.setColor(Color.GREEN);// 畫筆爲綠色
  50. mPaint.setStrokeWidth(1);// 設置畫筆粗細
  51. //示波器類庫
  52. clsOscilloscope.initOscilloscope(xMax/2, yMax/2, sfv.getHeight()/2);
  53. //縮放控件,X軸的數據縮小的比率高些
  54. zctlX = (ZoomControls)this.findViewById(R.id.zctlX);
  55. zctlX.setOnZoomInClickListener(new View.OnClickListener() {
  56. @Override
  57. public void onClick(View v) {
  58. if(clsOscilloscope.rateX>xMin)
  59. clsOscilloscope.rateX--;
  60. setTitle("X軸縮小"+String.valueOf(clsOscilloscope.rateX)+"倍"
  61. +","+"Y軸縮小"+String.valueOf(clsOscilloscope.rateY)+"倍");
  62. }
  63. });
  64. zctlX.setOnZoomOutClickListener(new View.OnClickListener() {
  65. @Override
  66. public void onClick(View v) {
  67. if(clsOscilloscope.rateX<xMax)
  68. clsOscilloscope.rateX++;
  69. setTitle("X軸縮小"+String.valueOf(clsOscilloscope.rateX)+"倍"
  70. +","+"Y軸縮小"+String.valueOf(clsOscilloscope.rateY)+"倍");
  71. }
  72. });
  73. zctlY = (ZoomControls)this.findViewById(R.id.zctlY);
  74. zctlY.setOnZoomInClickListener(new View.OnClickListener() {
  75. @Override
  76. public void onClick(View v) {
  77. if(clsOscilloscope.rateY>yMin)
  78. clsOscilloscope.rateY--;
  79. setTitle("X軸縮小"+String.valueOf(clsOscilloscope.rateX)+"倍"
  80. +","+"Y軸縮小"+String.valueOf(clsOscilloscope.rateY)+"倍");
  81. }
  82. });
  83. zctlY.setOnZoomOutClickListener(new View.OnClickListener() {
  84. @Override
  85. public void onClick(View v) {
  86. if(clsOscilloscope.rateY<yMax)
  87. clsOscilloscope.rateY++;
  88. setTitle("X軸縮小"+String.valueOf(clsOscilloscope.rateX)+"倍"
  89. +","+"Y軸縮小"+String.valueOf(clsOscilloscope.rateY)+"倍");
  90. }
  91. });
  92. }
  93. @Override
  94. protected void onDestroy() {
  95. super.onDestroy();
  96. android.os.Process.killProcess(android.os.Process.myPid());
  97. }
  98. /**
  99. * 按鍵事件處理
  100. * @author GV
  101. *
  102. */
  103. class ClickEvent implements View.OnClickListener {
  104. @Override
  105. public void onClick(View v) {
  106. if (v == btnStart) {
  107. clsOscilloscope.baseLine=sfv.getHeight()/2;
  108. clsOscilloscope.Start(audioRecord,recBufSize,sfv,mPaint);
  109. } else if (v == btnExit) {
  110. clsOscilloscope.Stop();
  111. }
  112. }
  113. }
  114. /**
  115. * 觸摸屏動態設置波形圖基線
  116. * @author GV
  117. *
  118. */
  119. class TouchEvent implements OnTouchListener{
  120. @Override
  121. public boolean onTouch(View v, MotionEvent event) {
  122. clsOscilloscope.baseLine=(int)event.getY();
  123. return true;
  124. }
  125. }
  126. }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章