Android 향상 시 뮬 레이 션 신호 오실로그래프 구현

11796 단어 Android
앞서 안 드 로 이 드 프로그램 개발 에서 AudioRecord 와 AudioTrack 의 사용 을 간단하게 소 개 했 고,이번 에는 Surface View 와 결합 해 안 드 로 이 드 버 전의 모 바 일 아 날로 그 신호 오실로그래프 를 구현 했다.최근 에 사물 인터넷 이 매우 잘 팔 리 는데 핸드폰 소프트웨어 개발 자로 서 어떻게 핸드폰 하드웨어 회 로 를 수정 하지 않 는 전제 에서 제3자 센서 와 결합 할 수 있 습 니까?마 이 크 는 아주 좋 은 ADC 인터페이스 로 마 이 크 를 통 해 제3자 센서 와 결합 한 다음 에 소프트웨어 에서 아 날로 그 신 호 를 상응 하 게 처리 하면 더욱 풍부 한 센서 화 응용 을 제공 할 수 있다.
먼저 본 프로그램 이 실행 하 는 효과 도 를 살 펴 보 자.

본 고 는 8000 hz 의 샘플링 율 을 사용 하여 X 축 방향 으로 그림 을 그 리 는 실시 성에 대한 요구 가 비교적 높 고 X 축의 해상 도 를 낮 추 지 않 으 면 프로그램의 실시 성 이 비교적 떨 어 지기 때문에 프로그램 이 X 축 데이터 에 대한 구간 을 8 배~16 배로 축소 한다.16 비트 샘플링 을 사용 하기 때문에 Y 축 데이터 의 높이 는 휴대 전화 화면 에 비해 크 고 프로그램 도 Y 축 데이터 에 대해 1 배~10 배 축소 되 었 다.Surface View 의 OnTouch Listener 방법 에 파형 기선 의 위치 조절 을 추가 하여 Surface View 컨트롤 에 직접 터치 하면 전체 파형 이 위로 치 우 치 거나 아래로 치 우 치 는 것 을 제어 할 수 있 습 니 다.
main.xml 원본 코드 는 다음 과 같 습 니 다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <LinearLayout android:id="@+id/LinearLayout01"
 android:layout_height="wrap_content" android:layout_width="fill_parent"
 android:orientation="horizontal">
 <Button android:layout_height="wrap_content" android:id="@+id/btnStart"
  android:text="  " android:layout_width="80dip"></Button>
 <Button android:layout_height="wrap_content" android:text="  "
  android:id="@+id/btnExit" android:layout_width="80dip"></Button>
 <ZoomControls android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/zctlX"></ZoomControls>
 <ZoomControls android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/zctlY"></ZoomControls>
 </LinearLayout>
 <SurfaceView android:id="@+id/SurfaceView01"
 android:layout_height="fill_parent" android:layout_width="fill_parent"></SurfaceView>
</LinearLayout>

ClosOscilloscope.java 는 오실로그래프 를 실현 하 는 라 이브 러 리 입 니 다.AudioRecord 작업 스 레 드 와 SurfaceView 그래 픽 스 레 드 의 실현 을 포함 하고 두 스 레 드 가 동기 화 되 며 코드 는 다음 과 같 습 니 다.

package com.testOscilloscope;
import java.util.ArrayList;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioRecord;
import android.view.SurfaceView;
public class ClsOscilloscope {
 private ArrayList<short[]> inBuf = new ArrayList<short[]>();
 private boolean isRecording = false;//       
 /**
 * X      
 */
 public int rateX = 4;
 /**
 * Y      
 */
 public int rateY = 4;
 /**
 * Y   
 */
 public int baseLine = 0;
 /**
 *    
 */
 public void initOscilloscope(int rateX, int rateY, int baseLine) {
 this.rateX = rateX;
 this.rateY = rateY;
 this.baseLine = baseLine;
 }
 /**
 *   
 * 
 * @param recBufSize
 *      AudioRecord MinBufferSize
 */
 public void Start(AudioRecord audioRecord, int recBufSize, SurfaceView sfv,
  Paint mPaint) {
 isRecording = true;
 new RecordThread(audioRecord, recBufSize).start();//       
 new DrawThread(sfv, mPaint).start();//       
 }
 /**
 *   
 */
 public void Stop() {
 isRecording = false;
 inBuf.clear();//   
 }
 /**
 *    MIC     inBuf
 * 
 * @author GV
 * 
 */
 class RecordThread extends Thread {
 private int recBufSize;
 private AudioRecord audioRecord;
 public RecordThread(AudioRecord audioRecord, int recBufSize) {
  this.audioRecord = audioRecord;
  this.recBufSize = recBufSize;
 }
 public void run() {
  try {
  short[] buffer = new short[recBufSize];
  audioRecord.startRecording();//     
  while (isRecording) {
   //  MIC        
   int bufferReadResult = audioRecord.read(buffer, 0,
    recBufSize);
   short[] tmpBuf = new short[bufferReadResult / rateX];
   for (int i = 0, ii = 0; i < tmpBuf.length; i++, ii = i
    * rateX) {
   tmpBuf[i] = buffer[ii];
   }
   synchronized (inBuf) {//
   inBuf.add(tmpBuf);//     
   }
  }
  audioRecord.stop();
  } catch (Throwable t) {
  }
 }
 };
 /**
 *     inBuf    
 * 
 * @author GV
 * 
 */
 class DrawThread extends Thread {
 private int oldX = 0;//      X  
 private int oldY = 0;//      Y  
 private SurfaceView sfv;//   
 private int X_index = 0;//         X    
 private Paint mPaint;//   
 public DrawThread(SurfaceView sfv, Paint mPaint) {
  this.sfv = sfv;
  this.mPaint = mPaint;
 }
 public void run() {
  while (isRecording) {
  ArrayList<short[]> buf = new ArrayList<short[]>();
  synchronized (inBuf) {
   if (inBuf.size() == 0)
   continue;
   buf = (ArrayList<short[]>) inBuf.clone();//   
   inBuf.clear();//   
  }
  for (int i = 0; i < buf.size(); i++) {
   short[] tmpBuf = buf.get(i);
   SimpleDraw(X_index, tmpBuf, rateY, baseLine);//          
   X_index = X_index + tmpBuf.length;
   if (X_index > sfv.getWidth()) {
   X_index = 0;
   }
  }
  }
 }
 /**
  *       
  * 
  * @param start
  *      X      (  )
  * @param buffer
  *         
  * @param rate
  *      Y        
  * @param baseLine
  *      Y   
  */
 void SimpleDraw(int start, short[] buffer, int rate, int baseLine) {
  if (start == 0)
  oldX = 0;
  Canvas canvas = sfv.getHolder().lockCanvas(
   new Rect(start, 0, start + buffer.length, sfv.getHeight()));//   :    
  canvas.drawColor(Color.BLACK);//     
  int y;
  for (int i = 0; i < buffer.length; i++) {//       
  int x = i + start;
  y = buffer[i] / rate + baseLine;//       ,     
  canvas.drawLine(oldX, oldY, x, y, mPaint);
  oldX = x;
  oldY = y;
  }
  sfv.getHolder().unlockCanvasAndPost(canvas);//     ,       
 }
 }
}

testOscilloscope.java 는 메 인 프로그램 으로 UI 와 Closcilloscope 를 제어 합 니 다.코드 는 다음 과 같 습 니 다.

package com.testOscilloscope;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ZoomControls;
public class testOscilloscope extends Activity {
  /** Called when the activity is first created. */
 Button btnStart,btnExit;
 SurfaceView sfv;
  ZoomControls zctlX,zctlY;
  
  ClsOscilloscope clsOscilloscope=new ClsOscilloscope();
  
 static final int frequency = 8000;//   
 static final int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
 static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
 static final int xMax = 16;//X        ,X      ,        
 static final int xMin = 8;//X        
 static final int yMax = 10;//Y        
 static final int yMin = 1;//Y        
 
 int recBufSize;//    buffer  
 AudioRecord audioRecord;
 Paint mPaint;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //    
 recBufSize = AudioRecord.getMinBufferSize(frequency,
  channelConfiguration, audioEncoding);
 audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,
  channelConfiguration, audioEncoding, recBufSize);
 //  
 btnStart = (Button) this.findViewById(R.id.btnStart);
 btnStart.setOnClickListener(new ClickEvent());
 btnExit = (Button) this.findViewById(R.id.btnExit);
 btnExit.setOnClickListener(new ClickEvent());
 //     
 sfv = (SurfaceView) this.findViewById(R.id.SurfaceView01); 
 sfv.setOnTouchListener(new TouchEvent());
    mPaint = new Paint(); 
    mPaint.setColor(Color.GREEN);//       
    mPaint.setStrokeWidth(1);//        
    //     
    clsOscilloscope.initOscilloscope(xMax/2, yMax/2, sfv.getHeight()/2);
    
    //    ,X           
 zctlX = (ZoomControls)this.findViewById(R.id.zctlX);
 zctlX.setOnZoomInClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  if(clsOscilloscope.rateX>xMin)
   clsOscilloscope.rateX--;
  setTitle("X   "+String.valueOf(clsOscilloscope.rateX)+" "
   +","+"Y   "+String.valueOf(clsOscilloscope.rateY)+" ");
  }
 });
 zctlX.setOnZoomOutClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  if(clsOscilloscope.rateX<xMax)
   clsOscilloscope.rateX++; 
  setTitle("X   "+String.valueOf(clsOscilloscope.rateX)+" "
   +","+"Y   "+String.valueOf(clsOscilloscope.rateY)+" ");
  }
 });
 zctlY = (ZoomControls)this.findViewById(R.id.zctlY);
 zctlY.setOnZoomInClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  if(clsOscilloscope.rateY>yMin)
   clsOscilloscope.rateY--;
  setTitle("X   "+String.valueOf(clsOscilloscope.rateX)+" "
   +","+"Y   "+String.valueOf(clsOscilloscope.rateY)+" ");
  }
 });
 
 zctlY.setOnZoomOutClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  if(clsOscilloscope.rateY<yMax)
   clsOscilloscope.rateY++; 
  setTitle("X   "+String.valueOf(clsOscilloscope.rateX)+" "
   +","+"Y   "+String.valueOf(clsOscilloscope.rateY)+" ");
  }
 });
  }
 @Override
 protected void onDestroy() {
 super.onDestroy();
 android.os.Process.killProcess(android.os.Process.myPid());
 }
 
 /**
 *       
 * @author GV
 *
 */
 class ClickEvent implements View.OnClickListener {
 @Override
 public void onClick(View v) {
  if (v == btnStart) {
  clsOscilloscope.baseLine=sfv.getHeight()/2;
  clsOscilloscope.Start(audioRecord,recBufSize,sfv,mPaint);
  } else if (v == btnExit) {
  clsOscilloscope.Stop();
  }
 }
 }
 /**
 *             
 * @author GV
 *
 */
 class TouchEvent implements OnTouchListener{
 @Override
 public boolean onTouch(View v, MotionEvent event) {
  clsOscilloscope.baseLine=(int)event.getY();
  return true;
 }
 }
}
본 논문 의 사례 가 독자 가 안 드 로 이 드 프로젝트 개발 을 하 는 데 어느 정도 참고 와 도움 이 되 기 를 바란다.

좋은 웹페이지 즐겨찾기