Android连接蓝牙录制pcm数据的示例代码
以下是Android连接蓝牙录制PCM数据的示例代码:
public class BluetoothRecorder {
private static final String TAG = "BluetoothRecorder";
private BluetoothAdapter mBluetoothAdapter;
private BluetoothSocket mBluetoothSocket;
private InputStream mInputStream;
private OutputStream mOutputStream;
private AudioRecord mAudioRecord;
private boolean mIsRecording;
private Thread mRecordingThread;
private byte[] mBuffer;
public BluetoothRecorder() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBuffer = new byte[1024];
}
public boolean connectToBluetoothDevice(String address) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
mBluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
mBluetoothSocket.connect();
mInputStream = mBluetoothSocket.getInputStream();
mOutputStream = mBluetoothSocket.getOutputStream();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void startRecording() {
mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 16000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, mBuffer.length);
mAudioRecord.startRecording();
mIsRecording = true;
mRecordingThread = new Thread(new Runnable() {
@Override
public void run() {
while (mIsRecording) {
int size = mAudioRecord.read(mBuffer, 0, mBuffer.length);
if (size > 0) {
try {
mOutputStream.write(mBuffer, 0, size);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
mRecordingThread.start();
}
public void stopRecording() {
mIsRecording = false;
try {
mRecordingThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
mAudioRecord.stop();
mAudioRecord.release();
mAudioRecord = null;
try {
mInputStream.close();
mOutputStream.close();
mBluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
此代码使用AudioRecord录制PCM数据,并将其写入BluetoothSocket的OutputStream。在连接到蓝牙设备后,可以调用startRecording()方法开始录制,调用stopRecording()方法停止录制并关闭BluetoothSocket
原文地址: http://www.cveoy.top/t/topic/eZEe 著作权归作者所有。请勿转载和采集!