Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play wav sound when click to button in wpf

Tags:

wpf

i want to play sound with click event of my button click event in my whole applciation,

i found 1 code that play sound when i click the button.

private void btn_Click(object sender, RoutedEventArgs e)
    {
        MediaPlayer mplayer = new MediaPlayer();
        mplayer.Open(new Uri("ding.wav", UriKind.Relative));
        mplayer.Play();
        //our code...
    }

i know this is not right solution, so please tell me if there are other solution, becoz i have to write this 3 line to each and every button click event and its tedious job.

please help to solve this problem.

waiting for reply...

thanks in advance

like image 391
Viral Sarvaiya Avatar asked May 11 '11 10:05

Viral Sarvaiya


1 Answers

Just define a style that plays the sound on the event PreviewMouseDown:

<Style TargetType="Button">
    <Style.Triggers>
        <EventTrigger RoutedEvent="PreviewMouseDown">
            <SoundPlayerAction Source="/ClickingButton;component/click.wav" />
        </EventTrigger>
    </Style.Triggers>
</Style>

See here for a discussion on why not to use Button.Click event in the event trigger. Basically, the problem is, that the Button.Click event is a bubbling one and the event trigger will be executed after the code in your normal click handler executed, i.e. the sound will have a delay, if your event handler does something that takes some time.

like image 94
Daniel Hilgarth Avatar answered Oct 15 '22 05:10

Daniel Hilgarth