如何使用 Windows UWP API 连接到已配对的音频蓝牙设备?

Pol*_*ear 8 c# windows bluetooth uwp

我想创建一个控制台替代“蓝牙和其他设备”对话框,该对话框内置于 Windows 中用于控制蓝牙设备。使用Windows.Devices.Enumeration API,我可以配对和取消配对设备。但是,蓝牙音频设备也具有连接功能(请参见下面的屏幕截图)。我希望我的应用程序能够复制当我按下此 UI 对话框中的“连接”按钮时所发生的情况。 在此输入图像描述

更新

目前,没有任何 API 可以用来解决我的问题。Github 上有一个关于这个主题的非常好的讨论,其中包含可用解决方案的描述并解释了它们不起作用的原因。

Pol*_*ear 6

到目前为止,我已经找到了允许 Windows 连接蓝牙音频设备的解决方法。它基于Bernard Moeskops 的回答。然而,要使其发挥作用,需要考虑以下因素:

  • 蓝牙音频设备可以注册为多个 PnP 设备,您需要切换每个设备。
  • 看来启用和禁用之间等待10秒是没有必要的。
  • “Disable-PnpDevice”和“Enable-PnpDevice”命令需要管理员权限。

我创建了一个适合我的 PowerShell 脚本(您需要将变量更改$headphonesName为您的音频设备的名称):

# "Disable-PnpDevice" and "Enable-PnpDevice" commands require admin rights
#Requires -RunAsAdministrator

# Substitute it with the name of your audio device.
# The audio device you are trying to connect to should be paired.
$headphonesName = "WH-1000XM3"

$bluetoothDevices = Get-PnpDevice -class Bluetooth

# My headphones are recognized as 3 devices:
# * WH-1000XM3
# * WH-1000XM3 Avrcp Transport
# * WH-1000XM3 Avrcp Transport
# It is not enough to toggle only 1 of them. We need to toggle all of them.
$headphonePnpDevices = $bluetoothDevices | Where-Object { $_.Name.StartsWith("$headphonesName") }

if(!$headphonePnpDevices) {
    Write-Host "Coudn't find any devices related to the '$headphonesName'"
    Write-Host "Whole list of available devices is:"
    $bluetoothDevices
    return
}

Write-Host "The following PnP devices related to the '$headphonesName' headphones found:"
ForEach($d in $headphonePnpDevices) { $d }

Write-Host "`nDisable all these devices"
ForEach($d in $headphonePnpDevices) { Disable-PnpDevice -InstanceId $d.InstanceId -Confirm:$false }

Write-Host "Enable all these devices"
ForEach($d in $headphonePnpDevices) { Enable-PnpDevice -InstanceId $d.InstanceId -Confirm:$false }

Write-Host "The headphones should be connected now."

# After toggling, Windows "Bluetooth devices" dialog shows the state of the headphones as "Connected" but not as "Connected voice, music"
# However, after some time (around 5 seconds), the state changes to "Connected voice, music".
Write-Host "It may take around 10 seconds until the Windows starts showing audio devices related to these headphones."
Run Code Online (Sandbox Code Playgroud)