android 怎么连接蓝牙录音示例代码
以下是一个简单的Android蓝牙录音示例代码,它可以连接到蓝牙设备并录制音频:
MainActivity.java
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_CODE = 2;
private static final String FILE_NAME = "recording.3gp";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter mBluetoothAdapter;
private BluetoothSocket mBluetoothSocket;
private OutputStream mOutputStream;
private MediaRecorder mMediaRecorder;
private Button mStartRecordingButton;
private Button mStopRecordingButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStartRecordingButton = findViewById(R.id.start_recording_button);
mStopRecordingButton = findViewById(R.id.stop_recording_button);
mStartRecordingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (checkPermissions()) {
startRecording();
} else {
requestPermissions();
}
}
});
mStopRecordingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopRecording();
}
});
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mBluetoothSocket != null) {
try {
mBluetoothSocket.close();
} catch (IOException e) {
Log.e(TAG, "Error closing Bluetooth socket", e);
}
}
}
private boolean checkPermissions() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
return ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
startRecording();
} else {
Toast.makeText(this, "Permissions not granted", Toast.LENGTH_LONG).show();
}
}
}
private void startRecording() {
try {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("00:11:22:33:44:55"); // replace with your Bluetooth device address
mBluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
mBluetoothSocket.connect();
mOutputStream = mBluetoothSocket.getOutputStream();
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setOutputFile(getFilePath());
mMediaRecorder.prepare();
mMediaRecorder.start();
mStartRecordingButton.setEnabled(false);
mStopRecordingButton.setEnabled(true);
Toast.makeText(this, "Recording started", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e(TAG, "Error connecting to Bluetooth device", e);
Toast.makeText(this, "Error connecting to Bluetooth device", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Log.e(TAG, "Error starting media recorder", e);
Toast.makeText(this, "Error starting media recorder", Toast.LENGTH_LONG).show();
}
}
private void stopRecording() {
try {
mMediaRecorder.stop();
mMediaRecorder.release();
mMediaRecorder = null;
mOutputStream.close();
mBluetoothSocket.close();
mStartRecordingButton.setEnabled(true);
mStopRecordingButton.setEnabled(false);
Toast.makeText(this, "Recording stopped", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e(TAG, "Error closing Bluetooth socket", e);
Toast.makeText(this, "Error closing Bluetooth socket", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Log.e(TAG, "Error stopping media recorder", e);
Toast.makeText(this, "Error stopping media recorder", Toast.LENGTH_LONG).show();
}
}
private String getFilePath() {
File directory = Environment.getExternalStorageDirectory();
return directory.getAbsolutePath() + "/" + FILE_NAME;
}
}
注意替换以下两个部分中的蓝牙设备地址:
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("00:11:22:33:44:55"); // replace with your Bluetooth device address
和
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
要连接到蓝牙设备,您需要在BluetoothAdapter上调用getRemoteDevice()方法,并传递设备的物理地址。然后,您需要使用该设备的createRfcommSocketToServiceRecord()方法创建一个BluetoothSocket对象。然后,您可以使用该对象的connect()方法连接到蓝牙设备。
一旦连接成功,您可以通过调用BluetoothSocket对象的getOutputStream()方法获取输出流。您可以将此输出流用作MediaRecorder的输出文件。录制音频后,关闭输出流和蓝牙套接字
原文地址: https://www.cveoy.top/t/topic/eZzI 著作权归作者所有。请勿转载和采集!