Skip to main content

Posts

Showing posts with the label Sound

Better way to play sound file on WPF button click

Recently I was working on a XAML based application, in which my requirement was to play a sound (.wav file) whenever a given button is clicked. So, to achieve this, I wrote a below snippet: My above snippet worked but at the same time, I feel a noticeable delay in beep sound and that make me analyze further and write a blog post :) Now question is, why there is delay between button click and sound ??? Well, there is a simple concept behind it, which I missed while implementing above requirement :( Reason is, the event hierarchy.  Most of us might be aware that Click is a bubbling event, which means event will be fired from the control who initiated it. So, in our case, whenever button is clicked, it bubbles from button to window. And that's the reason, click event handler is executing before the window event is triggered, which is ultimately leading to delay. Now, how to handle this??? Method 1: Then I thought to write a preview event, which will be fired