遇到客户一个需求,如果连接了带mic的蓝牙耳机,默认所有的录音要走蓝牙mic通道。
这个功能搞了好久,终于搞定了。
1. 向RK寻求帮助,先打通 bt sco能力。
此时,还无法默认就切换到蓝牙 mic通道,接下来我们需求默认切换到蓝牙通道。
2. 修改frameworks/av/services/audiopolicy/enginedefault/src/Engine.cpp,
默认走bt sco的mic录音输入源
switch (inputSource) {
case AUDIO_SOURCE_DEFAULT:
case AUDIO_SOURCE_MIC:
device = availableDevices.getDevice(
AUDIO_DEVICE_IN_BLUETOOTH_A2DP, String8(""), AUDIO_FORMAT_DEFAULT);
if (device != nullptr) break;
if (audio_is_bluetooth_out_sco_device(commDeviceType)) {
device = availableDevices.getDevice(
AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, String8(""), AUDIO_FORMAT_DEFAULT);
if (device != nullptr) break;
}
device = availableDevices.getFirstExistingDevice({
+ AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
AUDIO_DEVICE_IN_BLE_HEADSET, AUDIO_DEVICE_IN_WIRED_HEADSET,
AUDIO_DEVICE_IN_USB_HEADSET, AUDIO_DEVICE_IN_USB_DEVICE,
AUDIO_DEVICE_IN_BLUETOOTH_BLE, AUDIO_DEVICE_IN_BUILTIN_MIC});
break;
case AUDIO_SOURCE_CAMCORDER:
// For a device without built-in mic, adding usb device
device = availableDevices.getFirstExistingDevice({
- AUDIO_DEVICE_IN_USB_DEVICE,
+ AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, AUDIO_DEVICE_IN_USB_DEVICE,
AUDIO_DEVICE_IN_BACK_MIC, AUDIO_DEVICE_IN_BUILTIN_MIC});
break;
case AUDIO_SOURCE_VOICE_DOWNLINK:
3. 很关键的一步,在一个常驻service里边(或者可以在system ui模块实现)监听插入蓝牙耳机,进行默认sco模式切换
IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(myReceiver, filter);
BroadcastReceiver myReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(intent.getAction())) {Log.d("mod@bt", "bt connected");startBluetoothRecording(context);});} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(intent.getAction())) {Log.d("mod@bt", "bt disconnected");stopRecording(context);}}} };
public void startBluetoothRecording(Context context) {
try {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (!audioManager.isBluetoothScoOn()) {
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopRecording(Context context) {
try {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.isBluetoothScoOn()) {
audioManager.setBluetoothScoOn(false);
audioManager.stopBluetoothSco();
}
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setSpeakerphoneOn(true);
} catch (Exception e) {
e.printStackTrace();
}
}
4. 如上操作后,每次即使应用选择了系统默认mic,也会走bt sco通道录音。
5. 当然,可能会遇到其他的优化问题,如果你有需求,欢迎给我留言。