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

Android 提高第十篇:用 AudioRecord 與 AudioTrack 做一個「助聽器」

編輯:Android 開發實例

Android 上錄音有兩條路可走:MediaRecorder 直接把麥克風資料寫成檔案,還能順便編碼成 AMR、MP3 等格式;AudioRecord 則是取得原始的麥克風音訊串流,讓你自己決定怎麼處理。

本文走的是第二條路:用 AudioRecord 讀取音訊串流,用 AudioTrack 播放出來,靠「邊讀邊播」加上音量增益,就得到一個簡單的助聽器雛形。

要注意的是,當時的 Android 模擬器還不支援 AudioRecord,因此這個程式必須編譯後放到真機上執行。

權限要先申請

使用 AudioRecord 必須在 AndroidManifest.xml 中宣告錄音權限,少了這行會在執行期直接失敗:

<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>

畫面配置:main.xml

三顆按鈕分別負責開始邊錄邊播、停止與退出,下方一個 SeekBar 用來調整程式內部的播放音量:

<?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">

    <Button android:layout_height="wrap_content"
        android:id="@+id/btnRecord"
        android:layout_width="fill_parent"
        android:text="開始邊錄邊放"></Button>
    <Button android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="停止"
        android:id="@+id/btnStop"></Button>
    <Button android:layout_height="wrap_content"
        android:id="@+id/btnExit"
        android:layout_width="fill_parent"
        android:text="退出"></Button>

    <TextView android:id="@+id/TextView01"
        android:layout_height="wrap_content"
        android:text="程序音量調節"
        android:layout_width="fill_parent"></TextView>
    <SeekBar android:layout_height="wrap_content"
        android:id="@+id/skbVolume"
        android:layout_width="fill_parent"></SeekBar>
</LinearLayout>

testRecord.java:錄與播同時進行

重點在 RecordPlayThread:先啟動錄音與播放,然後在迴圈中不断把麥克風讀到的資料寫進 AudioTrack。因為是串流模式(AudioTrack.MODE_STREAM),寫入即播放,延遲取決於緩衝區大小。音量則透過 setStereoVolume() 控制,SeekBar 拖動結束後才套用新值,避免頻繁呼叫。

package com.testRecord;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;

public class testRecord extends Activity {

    Button btnRecord, btnStop, btnExit;
    SeekBar skbVolume;                  // 調節音量
    boolean isRecording = false;        // 是否錄放的標記

    static final int frequency = 44100;
    static final int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
    static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;

    int recBufSize, playBufSize;
    AudioRecord audioRecord;
    AudioTrack audioTrack;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setTitle("助聽器");

        recBufSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
        playBufSize = AudioTrack.getMinBufferSize(frequency, channelConfiguration, audioEncoding);

        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,
                channelConfiguration, audioEncoding, recBufSize);
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, frequency,
                channelConfiguration, audioEncoding,
                playBufSize, AudioTrack.MODE_STREAM);

        btnRecord = (Button) this.findViewById(R.id.btnRecord);
        btnRecord.setOnClickListener(new ClickEvent());
        btnStop = (Button) this.findViewById(R.id.btnStop);
        btnStop.setOnClickListener(new ClickEvent());
        btnExit = (Button) this.findViewById(R.id.btnExit);
        btnExit.setOnClickListener(new ClickEvent());

        skbVolume = (SeekBar) this.findViewById(R.id.skbVolume);
        skbVolume.setMax(100);          // 音量調節上限
        skbVolume.setProgress(70);      // 初始位置
        audioTrack.setStereoVolume(0.7f, 0.7f);
        skbVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                float vol = (float) (seekBar.getProgress()) / (float) (seekBar.getMax());
                audioTrack.setStereoVolume(vol, vol);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) { }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }
        });
    }

    @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 == btnRecord) {
                isRecording = true;
                new RecordPlayThread().start();     // 開一條線程邊錄邊放
            } else if (v == btnStop) {
                isRecording = false;
            } else if (v == btnExit) {
                isRecording = false;
                testRecord.this.finish();
            }
        }
    }

    class RecordPlayThread extends Thread {
        public void run() {
            try {
                byte[] buffer = new byte[recBufSize];
                audioRecord.startRecording();       // 開始錄製
                audioTrack.play();                  // 開始播放
                while (isRecording) {
                    // 從 MIC 讀資料到緩衝區
                    int bufferReadResult = audioRecord.read(buffer, 0, recBufSize);
                    byte[] tmpBuf = new byte[bufferReadResult];
                    System.arraycopy(buffer, 0, tmpBuf, 0, bufferReadResult);
                    // 寫入即播放
                    audioTrack.write(tmpBuf, 0, tmpBuf.length);
                }
                audioTrack.stop();
                audioRecord.stop();
            } catch (Throwable t) {
                Toast.makeText(testRecord.this, t.getMessage(), 1000).show();
            }
        }
    }
}

兩個實務上的提醒

第一,程式內的 SeekBar 只能調整 App 自己的播放音量,若要真正的最大音量,仍必須另外用實體音量鍵或 AudioManager 去調系統音量。第二,把取樣率、緩衝區大小與声道設定三個參數保持一致,是 AudioRecord 與 AudioTrack 能穩定協作的基礎;參數不合容易出現爆音或讀寫不同步。若把這個「讀了就播」的迴圈再加上簡單的濾波或增益運算,就能延伸成更多音訊處理的小工具。

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