CSharp .Net Tutorial: Playing Simultaneous Sounds

James Cloud
Playing sounds using API works. However you will not be able to play two or more sounds at the same time. For example, you might want to play a sound effect and not interrupt your music while doing so. You can use the Windows Media Player library to overcome this quite easily.

This tutorial will show you how to create a function that will allow you to easily play sounds simultaneously at anytime during your applications runtime. Just follow the instructions given below.

Playing Simultaneous Sounds

Because this method uses the .Net Window's Media Player library your will have to add a references to Windows Media Play in your project. This is quite a simple task, just:

Click Projects and select add Reference. Then select the COM tab and find Windows Media Play, select it and press OK.

Also add this code above your namespace:

using WMPLib;

With all the proper references you can now construct your sounds playing method. Create a void called PlayFile with two parameters, one for the File Path and the other for the volume. Use this code to make the function:

public void PlayFile(String FilePath, int Volume)
{
WindowsMediaPlayer myWMP = new WindowsMediaPlayer();

myWMP.windowlessVideo = true;
myWMP.uiMode = "none";

myWMP.URL = FilePath;

myWMP.settings.volume = Volume;

myWMP.controls.play();
}

Conclusion

To play two files or more during the same time, or simultaneously, simply call the PlayFile method and supply the path to your desired file and the volume level, 1 through 100, you wish to play it at. Here is an example usage of the PlayFile function:

PlayFile("C:\\My Music\\Rock.wav", 100);
PlayFile("C:\\My Music\\Jazz.wav", 50);

This example will play the Rock.wav file at the same time as the Jazz.wav file but at double the volume. The PlayFile method supports all major music and sound file formats such as .mp3, .wav, .ect.

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.