× Main Menu

WPF C# Tutorial – Playing Audio Files with Sound Player and Media Player in Visual Studio

In this tutorial we will show you two different methods to play audio files in WPF C#. The first method will be something we have used before in our Windows Form Application tutorials, it’s called the sound player it allows us to play single files or loop the files. Second method to be used will be the media player from the new dot net framework this one allows us to use URI methods to find the files and play them as a stream. Let’s get to it.

Lesson Objective –

  1. Create a sound player app in Visual Studio with WPF and C#
  2. Use system media name space which allows us to use the sound player class
  3. Creating new instances of sound player and media player classes
  4. Import sound file to the resources
  5. Import sound file to the project file hierarchy
  6. Linking buttons and events to play the sound files

First let’s make a new visual studio project. Under C# choose WPF App. Name the project play sound and click OK.

Below is the empty project opened in visual studio. The first part is the preview file and second part is the XML file for the design where we can insert buttons and other components for the app.

Below is the default XML values. We will start to edit this file and add our own code in the XML.

Below is the edited XML file. Let’s take a closer look.

First we are giving this app a title “Play Sound in WPF”.

After that we have the GRID panel which now contains another option called background it will have the background colour of forest green.

Inside the GRID we have two buttons, both button are very similar but they have some key differences. First each of them have their own CLICK events connected to them, the first button has an event called playsoundOne and second button has an event called playsoundTwo. They will have their own respective button content which is the text that shows inside the buttons.

Above is the view of the form so far. You can see both of the buttons are showing in the form now. the background colour has been applied to the form as well.


Comment on this tutorial and let us know how you got on -

%d bloggers like this: