[AGDev-newbies] Loading and playing sounds in C#.net.

Thomas Ward tward1978 at earthlink.net
Sun May 7 05:23:58 BST 2006


Hi all.
This again is an area where C#.net takes something, and makes it a real 
breeze. Loading and setting up sound files in C#.net is easy as cake or 
is it easy as pie.Well, either way I can practically reproduce the 
instructions in C#.net right off my head. Here is a ruff idea of the 
procedure. It is not a complete program, but a basic outline of  just 
the DirectX stuff. I'll prefect this program and offer the complete 
source code when I do the tutorial for the wiki.

Using Microsoft.DirectX;
Using Microsoft.DirectX.DirectSound;

public class Form1: System.Windows.Forms.Form
{

// DirectX sound object.
private Device g_audio = null;

// DirectX sound object.
private SecondaryBuffer g_sound = null;


// Buffer description object.
BufferDescription g_description = null;


// Load audio method.
// Sets up the sound card and sound files
// for playback.
public void LoadAudio()
{

// Create new instances of
// the audio device.
g_audio = new Device();

// Set cooperative levels.
g_audio.SetCooperativeLevel(CooperativeLevelFlags.Background | 
CooperativeLevelFlags.NonExclusive);

// Acquire the sound card for playback.
g_audio.Acquire();


// Set up sound buffer description.
// The options set weather the sound can be panned,
// positioned in 3D,
// frequency can be changed,
// and other options.
g_description = new BufferDescription();

// Turn on virtual 3D processing.
g_description.Control3D = true;

// Turn on frequency changes.
g_description.ControlFrequency = true;

// Load our sound in to the g_sound buffer.
g_sound = new
(@"sound.wav", g_description, g_audio);
}

// Start sound.
// Starts the loaded sound to playing,
// and loops until stopped.
public void StartSound()
{
g_sound.Play(0, BufferPlayFlags.Looping);
}


// Main function.
// Entry point for the
// C#.net application.
public void Main()
{
using(Form1 form = new Form1())
{

// Load the audio stuff.
form.LoadAudio();

// Start playing the sound.
form.StartSound();

// Run the program.
Application.Run(form);
}
}
}


There you go. that is all there is to loading a sound on the DirectX 
end. What i left out was all the code which make the form run, and work 
as a normal Window. For sound instructions it isn't necessary, but will 
be when doing games.
As I said when I finish with the real finished tutorial the instructions 
will be a complete working program, and you will be able to view the 
entire source, and it will obviously be tested for errors. However, 
since many of you wanted to see how it is done, in C#.net this is a very 
simple task.





More information about the AGDev-newbies mailing list