Skip to content

Update Engine.Audio.cs - Fix audio halt and deadlock on audio device switch#693

Open
OceanCyanTech wants to merge 1 commit into
SuRGeoNix:masterfrom
OceanCyanTech:OceanCyanTech-fix-audio-deadlock
Open

Update Engine.Audio.cs - Fix audio halt and deadlock on audio device switch#693
OceanCyanTech wants to merge 1 commit into
SuRGeoNix:masterfrom
OceanCyanTech:OceanCyanTech-fix-audio-deadlock

Conversation

@OceanCyanTech
Copy link
Copy Markdown

This pull request is for a critical issue/bug where switching audio devices (e.g., connecting or disconnecting earphones or headphones into the audio port) causes the audio playback to stall, the seek bar to break. This behavior was observed in both WinUI 3 and WPF framework.

Root Cause:
Deadlock: Attempting to update player.Audio.Device on the UI thread leads to a deadlock during the xaudio.Dispose() process.

Logic Gap: The previous RefreshDevices method only forced a device update when a device was removed. Which caused no switch in the audio device and player refused to play with no error code or output.

Changes:
Offloaded Device Switching: Moved the assignment of player.Audio.Device to a background Task.Run to decouple it from the UI thread and prevent xaudio.Dispose() deadlocks.

Proactive Default Sync: Added a check to detect and identify when the system's default multimedia Endpoint changes. The engine now switches to the current/new Default regardless of whether an audio device was added or removed.

Slight Delay: Added a 200ms Thread.Sleep before re-initialization to allow OS/Realtek drivers to stabilize and refresh after a device connect/disconnect.

Some Code Cleanup: Now that i have consolidated the logic into a single source of code based on the current Default device Id, I have commented the code that could have potentially caused clash with the new code and then infinite loops. If you feel that code is no longer necessary, you can remove it. I have tested the new code in the sample player before testing in my own app, by repetitively connecting and disconnecting my headphones and it worked fine with just a tiny break. Other than that, everything else would work fine, I hope.

Please do review the changes i made and consider possibly integrating them into the official release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant