Adding sound effects to WPF Surface application

2.3k views Asked by At

I am trying to play a sound whenever an object is touched/moved in my WPF Surface application, to depict it has been selected or its movement. Here is what I tried but it doesn't seem to work.

SoundPlayerAction soundPlayerAction = new SoundPlayerAction();
soundPlayerAction.Source = new Uri(@"C:\Resources\Selection.wav", UriKind.RelativeOrAbsolute);
EventTrigger eventTrigger = new EventTrigger(TouchEnterEvent); // this is the event you want to trigger the sound effect.
eventTrigger.Actions.Add(soundPlayerAction);

Any feedback or ideas will be much appreciated.

3

There are 3 answers

0
Mehmed On

Create a new folder in your project and rename it to SOUNDS then insert your sound files in it and try this:

  SoundPlayerAction soundPlayerAction = new SoundPlayerAction();
    soundPlayerAction.Source = new Uri(@"SOUNDS\Selection.wav", UriKind.RelativeOrAbsolute);


    EventTrigger eventTrigger = new EventTrigger(TouchEnterEvent); // this is the event you want to trigger the sound effect.

    eventTrigger.Actions.Add(soundPlayerAction);
     Triggers.Add(eventTrigger); // Add this event trigger to Window.Triggers collection.
1
Clemens On

C:\Resources\Selection.wav is obviously not the correct path of the sound file.

You should create a folder named "Resources" in your Visual Studio project, and add the sound file to that folder. Then go to the properties of the sound file and set its Build Action to Resource and also set Copy to Output Directory to Copy aways or Copy if newer.

Now you can access the file by a relative Uri like this:

soundPlayerAction.Source = new Uri("Resources/Selection.wav", UriKind.Relative);
0
Naaz On

I came across this link https://www.youtube.com/watch?v=nF-HYoTurc8 and somewhat changed my code and the sound worked :D

In my PreviewTouchDown method, I added:

SoundPlayer soundPlayerAction = new SoundPlayer(TangramsTool.Properties.Resources.Selection);
soundPlayerAction.Play();