C# – WPF – Dropdown menus & audio combination

In this article I present the combination of a drop-down menu and audio in a WPF application. Simply, the application’s logic is the following – you select one media file from a drop-down list and then you play it. The playing of the file is helped by the class SoundPlayer, which has the following interesting methods and properties:

> Play(): Plays a WAV file in a way that other actions can be carried out in the same time;

> PlaySync(): This action does not allow other actions in the same time & it cannot be paused;

> PlayLooping(): This is just a looping action, which may be paused;

> Stop(): A good way to stop PlayLooping() or Play();

> Load(): A good way to load a WAV file, which will be played with PlaySync();

> LoadAsync(): Loads a file to be played with Play() or PlayLooping();

> SoundLocation -> this is a property, telling us the path and the file name of the file.

So, the application looks like this:

sounds

 

The idea is as mentioned above – you can select which file through which method you would like to play. The button of the method “PlaySync()” is colored, because once you run it you cannot stop it :). Even with the red “X” on the top right corner of the window. If you want to hear a system sound, you may press the button “System Sound”. For a reason, the only play method the system sounds have is “Play()”.

Long story short, here is the XAML code of the application:

Here is the C# code:

In the C# code, it is a good practice to not the small “change()” method, which actually tells the compiler to look for a file, named with the value of the drop-down menu in the folder of the application. If such file is not found:

then the application does not do anything. Last but not least, here is the application.

Enjoy the code 🙂

Tagged with: , , , , , ,