Android AAudio支持實時錄音。AAudio是Android平臺上的一個音頻API,它在Android 10中被引入,旨在提供低延遲、高保真度的音頻處理能力。AAudio特別適用于需要實時音頻處理的場景,如語音識別、實時音頻處理、游戲音效等。
使用AAudio進行實時錄音時,需要注意以下幾點:
下面是一個簡單的AAudio實時錄音示例代碼:
import android.Manifest;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int SAMPLE_RATE_IN_HZ = 44100;
private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private static final int BUFFER_SIZE_IN_BYTES = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG, AUDIO_FORMAT);
private AudioRecord audioRecord;
private HandlerThread handlerThread;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 檢查錄音權限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
} else {
startRecording();
}
}
private void startRecording() {
handlerThread = new HandlerThread("AudioRecordThread");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG, AUDIO_FORMAT, BUFFER_SIZE_IN_BYTES);
if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
// 初始化失敗,處理錯誤
} else {
audioRecord.startRecording();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// 錄音結束,處理音頻數據
audioRecord.stop();
}
}, 10000); // 延遲10秒后停止錄音
}
}
}
請注意,這只是一個簡單的示例代碼,實際應用中可能需要根據具體需求進行調整。同時,為了確保音頻數據的實時處理,建議在單獨的線程中進行音頻錄制和播放操作。