Why does AudioPlaybackConnection keep disconnecting from Bluetooth devices in non-UWP applications?

Brian Mak 1 Reputation point
2020-12-07T03:54:33.293+00:00

I've created a test method in C# to connect to Bluetooth devices through the newly introduced AudioPlaybackConnection class in the WinRT API. I see that AudioPlaybackConnection is marked with the DualApiPartition attribute, so it should work in desktop applications. However, for some reason, it keeps pausing the audio and disconnecting from the Bluetooth device after about five seconds of playing. I am currently trying this on .NET 5. I have tried rolling back to .NET Core 3.1 and getting the NuGet package for the WinRT API, but the same thing happens. The disconnecting does not happen when using the same code in a UWP application. This only happens in my non-UWP testing application.

Below is the piece of test code I've created:

private async void Test( )
{
    Dictionary<string, AudioPlaybackConnection> audioPlaybackConnections = new Dictionary<string, AudioPlaybackConnection>( );
    ObservableCollection<DeviceInformation> devices = new ObservableCollection<DeviceInformation>( );
    DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher( AudioPlaybackConnection.GetDeviceSelector( ) );
    deviceWatcher.Added += ( DeviceWatcher sender, DeviceInformation device ) => devices.Add( device );

    deviceWatcher.Removed += ( DeviceWatcher sender, DeviceInformationUpdate deviceUpdate ) =>
    {
        foreach ( DeviceInformation device in devices )
        {
            if ( device.Id == deviceUpdate.Id )
            {
                devices.Remove( device );
            }
        }

        if ( audioPlaybackConnections.ContainsKey( deviceUpdate.Id ) )
        {
            audioPlaybackConnections[ deviceUpdate.Id ].Dispose( );
            audioPlaybackConnections.Remove( deviceUpdate.Id );
        }
    };

    deviceWatcher.Start( );
    await Task.Delay( 5000 );
    var test = AudioPlaybackConnection.TryCreateFromId( devices[ 1 ].Id );
    test.Start( );
    test.Open( );
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,362 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,130 questions
0 comments No comments
{count} votes