基于低功耗蓝牙 (BLE) 音频的蓝牙音频配置文件允许双向流式传输高品质音频(例如,采样率为 32 kHz 的立体声音频)。这得益于 LE 等时通道 (ISO) 的创建。ISO 与同步面向连接 (SCO) 链路类似,因为它也使用预留的无线带宽,但带宽预留不再限制为 64 Kbps,而是可以动态调整。
蓝牙音频输入几乎可以针对所有用例(不包括通话)使用 AudioManager API。本指南介绍了如何通过 BLE Audio 可穿戴式耳机录制立体声音频。
配置您的应用
首先,在 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 指南中的说明录制音频。