以编程方式连接到配对的蓝牙扬声器并播放音频
2022-09-04 21:24:24
在我们的应用程序中,我想使用 Android v4.2 或更高版本连接到以前配对的 A2DP 蓝牙音箱,并直接播放音频。
我可以使用此代码成功创建 A2DP 配置文件对象来启动该过程:
/* Manifest permissions */
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.A2DP)
并有以下监听器响应连接:
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothSpeaker = (BluetoothA2dp) proxy;
// no devices are connected
List<BluetoothDevice> connectedDevices = mBluetoothSpeaker.getConnectedDevices();
//the one paired (and disconnected) speaker is returned here
int[] statesToCheck = {BluetoothA2dp.STATE_DISCONNECTED};
List<BluetoothDevice> disconnectedDevices = mBluetoothSpeaker.getDevicesMatchingConnectionStates(statesToCheck);
BluetoothDevice btSpeaker = disconnectedDevices.get(0);
//WHAT NOW?
}
}
public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothSpeaker = null;
}
}
};
我只是有点迷失了现在该做什么,连接设备,并将音频输出定向到它。我尝试使用以下代码连接到Android文档中的设备,但最终调用未返回任何连接的设备。BluetoothSpeaker.getConnectedDevices()
BluetoothSocket tmp = null;
UUID MY_UUID = UUID.fromString("00001108-0000-1000-8000-00805f9b34fb");
try {
tmp = btSpeaker.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.d("createRfcommSocketToServiceRecord ERROR", e1.getMessage());
}
mmSocket = tmp;
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
Log.d("connectException", connectException.getMessage());
mmSocket.close();
} catch (IOException closeException) { }
return;
}
connectedDevices = mBluetoothSpeaker.getConnectedDevices();
代码似乎以某种方式连接到设备,因为当我停止执行时,蓝牙扬声器会宣布它已准备好配对(就像它与音频源断开连接时一样)。
旧版本的似乎有一个方法,但现在已经被删除(从4.2开始),我正在努力寻找任何关于如何以编程方式连接到A2DP设备并将音频输出定向到它的清晰示例。任何关于如何接近任何一个的帮助将不胜感激。BluetoothA2dp
connect(BluetoothDevice device)
任何关于如何解决这个问题的建议将不胜感激。