Csharp.Net Tutorial: Playing Audio with DirectX

James Cloud
Introduction

Music and sound effect and essential in games and various other projects. If you cannot afford or find a sound library for Csharp .Net you can use DirectX to incorporate audio into your projects. Using DirectX and Direct Sound it is possible to even make your own media player.

This tutorial will show you a simple, easy to implement, and reliable method to playing sounds and music in your projects or games in Csharp.net.

References

A reference to Mircosft DirectX DirectSound is required to use directx for playing audio files. To add the Direct Sound reference to your project follow these simple steps,

1. Click the Project menu button and select Add Reference.
2. Under the .Net tab find and double click the enrty entitled, "Mircosoft.DirectX.DirectSound".

Loading and Playing

You firstly need to define an audio device in which to actually play audio buffers. Define a device in your projects declaration code as so,

Device AudioDevice = new Device();

Now that the proper audio device has been created it is time to define an actual audio buffer that will load and play sound files. Define a sound buffer in your declaration using this format,

SecondaryBuffer snd_Mysound;

Before the new sound buffer can be accessed using the defined device you will need to set the devices cooperation level to the appropriate priority. Use this source to prioritize the device,

AudioDevice.SetCooperativeLevel(this, CooperativeLevel.Priority);

Now load the desired audio file into the sound buffer,

snd_Mysound = new SecondaryBuffer(Application.StartupPath + "\\Sounds\\mysound.wav", AudioDevice);

To play the sound once it is loaded execute the this code,

snd_Mysound.Play(0, BufferPlayFlags.Default);

Conclusion

Using the method described above you can play many audio files in a more reliable way then using windows media player or other method.

If you want to loop a sound, such as music, send the Buffer flag looping.

snd_Mysound.Play(0, BufferPlayFlags.Looping);

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.