Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 提高第十一篇:動手做一支手機版模擬訊號示波器

編輯:Android 開發實例

上一篇簡單介紹了 AudioRecord 與 AudioTrack 的用法,這次把它和 SurfaceView 結合起來,做一支 Android 版的手機示波器(先前也談過 J2ME 版的實作)。

物聯網話題正熱,身為手機軟體開發者,要如何在不改動手機硬體電路的前提下與第三方傳感器結合?麥克風就是一個現成的 ADC 入口——透過麥克風接入類比訊號,再在軟體裡做相應處理,就能延伸出各種有趣的感測應用。

取捨:犧牲一點解析度換取即時性

程式採用 8000Hz 取樣率。X 軸方向的繪圖即時性要求很高,如果不降低 X 軸解析度,畫面會明顯落後,因此程式把 X 軸資料壓縮為 8 到 16 倍。另一方面,16 位取樣讓 Y 軸的數值範圍遠大於螢幕高度,所以 Y 軸也需要縮小,區間設定為 1 到 10 倍。

此外,在 SurfaceView 的 OnTouchListener 中加入了波形基線位置的調節——直接在畫面上觸摸,就能讓整條波形往上或往下移動,對觀察不同振幅的訊號相當方便。(附圖為螢幕錄影,速度偏慢,真機執行會更順暢。)

畫面配置:main.xml

上方一列是開始、停止與兩組 ZoomControls(分別控制 X 軸與 Y 軸縮放),下方大面積留給 SurfaceView 當畫布:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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>

ClsOscilloscope.java:示波器核心類別

這個類別封裝了兩條同步協作的線程:RecordThread 持續從麥克風取樣並寫入共享緩衝區,DrawThread 則把緩衝區中的資料畫到 SurfaceView 上。兩邊以 synchronized (inBuf) 保護共享資料,繪圖時先把 inBuf 複製一份再清空,避免互相等待造成卡頓。

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;    // 線程控制標記

    public int rateX = 4;      // X 軸縮小比例
    public int rateY = 4;      // Y 軸縮小比例
    public int baseLine = 0;   // Y 軸基線

    /** 初始化 */
    public void initOscilloscope(int rateX, int rateY, int baseLine) {
        this.rateX = rateX;
        this.rateY = rateY;
        this.baseLine = baseLine;
    }

    /** 開始,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 */
    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) {
                    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 中的資料 */
    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 控制

主程式負責建立 AudioRecord、準備畫筆、把四組縮放按鈕接到 rateX 與 rateY 上,並在標題列即時顯示目前的縮小倍率。X 軸的縮放範圍刻意設得比 Y 軸大(8 到 16 倍),因為 X 軸資料量龐大,最容易造成刷新延遲。

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 {

    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 軸縮小比例最大值,資料量大易造成刷新延遲
    static final int xMin = 8;    // X 軸縮小比例最小值
    static final int yMax = 10;   // Y 軸縮小比例最大值
    static final int yMin = 1;    // Y 軸縮小比例最小值

    int recBufSize;
    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軸縮小" + clsOscilloscope.rateX + "倍," + "Y軸縮小" + clsOscilloscope.rateY + "倍");
            }
        });
        zctlX.setOnZoomOutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clsOscilloscope.rateX < xMax)
                    clsOscilloscope.rateX++;
                setTitle("X軸縮小" + clsOscilloscope.rateX + "倍," + "Y軸縮小" + clsOscilloscope.rateY + "倍");
            }
        });

        // Y 軸縮放
        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軸縮小" + clsOscilloscope.rateX + "倍," + "Y軸縮小" + clsOscilloscope.rateY + "倍");
            }
        });
        zctlY.setOnZoomOutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clsOscilloscope.rateY < yMax)
                    clsOscilloscope.rateY++;
                setTitle("X軸縮小" + clsOscilloscope.rateX + "倍," + "Y軸縮小" + clsOscilloscope.rateY + "倍");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /** 按鍵事件 */
    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();
            }
        }
    }

    /** 觸摸螢幕動態設定波形基線 */
    class TouchEvent implements OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            clsOscilloscope.baseLine = (int) event.getY();
            return true;
        }
    }
}

效能上的兩個關鍵細節

第一,lockCanvas(Rect) 只鎖定即將繪製的窄區域,而不是整塊螢幕,這對幀率影響很大。第二,取樣與繪製拆成兩條線程,並用「先複製再清空」的方式交換資料,讓繪圖端不會被取樣端拖住。這兩個技巧在任何需要即時繪圖的 Android 應用裡都通用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved