关键是调用audioManager.startBluetoothSco()。
此方法可用于希望在电话未通话时向/从蓝牙 SCO 耳机发送和接收音频的应用程序。
这是一个异步操作,因此,您可以注册一个BroadcastReceiver
以在开始通过蓝牙耳机录制音频时收到通知,就像这样
private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
// Start recording audio
}
}
};
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.startBluetoothSco();
}
文档还提到了一些非常重要的事情
应用程序可以在调用 startBluetoothSco() 之前通过读取接收器注册返回的意图来检查 SCO 音频状态。如果状态已经 CONNECTED,则在调用 startBluetoothSco() 后不会通过意图接收到状态更改。
和...
然而,调用 startBluetoothSco() 很有用,以便在当前启动器停止连接的情况下连接保持活动状态。
这意味着如果 SCO 连接已经处于活动状态,您不必等待接收方被调用。这是更新的代码片段。
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
Intent intent = registerReceiver(mBluetoothScoReceiver, intentFilter);
if (intent == null) {
Log.e(TAG, "Failed to register bluetooth sco receiver...");
return;
}
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
// Start recording
}
// Ensure the SCO audio connection stays active in case the
// current initiator stops it.
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.startBluetoothSco();
}
如果您不使用它,您应该停止 SCO 连接。
private void onPause() {
super.onPause();
unregisterReceiver(mBluetoothScoReceiver);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.stopBluetoothSco();
}
您的AndroidManifest.xml
文件中还需要以下权限
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>