录音

基于蓝牙低功耗 (BLE) 音频的蓝牙音频配置文件允许双向流式传输高质量的音频(例如,采样率为 32 kHz 的立体声音频)。这要归功于 LE 等时通道 (ISO) 的创建。ISO 与面向同步连接 (SCO) 链路类似,因为它也使用预留的无线带宽,但带宽预留不再是 64 Kbps 的上限,可以动态调整。

蓝牙音频输入可以在几乎所有用例(不包括通话)中使用最新的 AudioManager API。本指南介绍了如何通过 BLE 音频耳机录制立体声音频。

配置应用

首先,将您的应用配置为以 build.gradle 中的正确 SDK 为目标平台:

targetSdkVersion 31

注册音频回调

创建 AudioDeviceCallback,让应用了解已连接或断开连接的 AudioDevices 的任何变化。

final AudioDeviceCallback audioDeviceCallback = new AudioDeviceCallback() {
  @Override
  public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
    };
  @Override
  public void onAudioDevicesRemoved(AudioDeviceInfo[] removedDevices) {
    // Handle device removal
  };
};

audioManager.registerAudioDeviceCallback(audioDeviceCallback);

查找 BLE 音频设备

获取支持输入的所有已连接音频设备的列表,然后使用 getType() 通过 AudioDeviceInfo.TYPE_BLE_HEADSET 查看设备是否为耳机。

Kotlin

val allDeviceInfo = audioManager.getDevices(GET_DEVICES_INPUTS)
var bleInputDevice: AudioDeviceInfo? = null
  for (device in allDeviceInfo) {
    if (device.type == AudioDeviceInfo.TYPE_BLE_HEADSET) {
      bleInputDevice = device
      break
    }
  }

Java

AudioDeviceInfo[] allDeviceInfo = audioManager.getDevices(GET_DEVICES_INPUTS);
AudioDeviceInfo bleInputDevice = null;
for (AudioDeviceInfo device : allDeviceInfo) {
  if (device.getType() == AudioDeviceInfo.TYPE_BLE_HEADSET) {
    bleInputDevice = device;
    break;
  }
}

立体声支持

如需检查所选设备是否支持立体声麦克风,请查看设备是否具有两个或更多声道。如果设备只有一个声道,请将声道掩码设置为单声道。

Kotlin

var channelMask: Int = AudioFormat.CHANNEL_IN_MONO
if (audioDevice.channelCounts.size >= 2) {
  channelMask = AudioFormat.CHANNEL_IN_STEREO
}

Java

if (bleInputDevice.getChannelCounts() >= 2) {
  channelMask = AudioFormat.CHANNEL_IN_STEREO;
};

设置录音机

您可以使用标准 AudioRecord 构建器设置录音器。您可以使用声道掩码选择立体声或单声道配置。

Kotlin

val recorder = AudioRecord.Builder()
  .setAudioSource(MediaRecorder.AudioSource.MIC)
  .setAudioFormat(AudioFormat.Builder()
    .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
    .setSampleRate(32000)
    .setChannelMask(channelMask)
    .build())
  .setBufferSizeInBytes(2 * minBuffSizeBytes)
  .build()

Java

AudioRecord recorder = new AudioRecord.Builder()
  .setAudioSource(MediaRecorder.AudioSource.MIC)
  .setAudioFormat(new AudioFormat.Builder()
    .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
    .setSampleRate(32000)
    .setChannelMask(channelMask)
    .build())
  .setBufferSizeInBytes(2*minBuffSizeBytes)
  .build();

设置首选设备

设置首选设备会告知音频 recorder 您要使用哪个音频设备进行录制。

Kotlin

recorder.preferredDevice = audioDevice

Java

recorder.setPreferredDevice(bleInputDevice);

现在,您可以按照 MediaRecorder 指南中的说明录制音频。