# Playing audio files using C#



## MrSeanKon (May 13, 2008)

First of all *go here and download* the source code.
 Kreij help!!! 
I would like to update my cardgames that's the main reason.
To be more specific I am thinking to create a professional Preference edition.
Anyway the attachment file shows clearly what I want to do.
If I add a *.wav file (like a recourse so it is hidden) I don't know how can I play it!


----------



## Deleted member 3 (May 13, 2008)

system.media.soundplayer.play()?


----------



## Deleted member 3 (May 13, 2008)

Forget the question mark, I tested it

In vb it's:


> Dim bla As New System.Media.SoundPlayer(My.Resources.chimes)
> bla.Play()


Of course chimes is the windows chimes.wav, I added it as resource.

Translate it to C yourself.


----------



## Kreij (May 13, 2008)

Why are you calling unmanaged code (winmm.dll) from a managed C# application (causing trust problems and in general making your life much more difficult? I would use either the DirectX audio API or the XNA XACT libraries (or the System.Media namespace as Dan suggested).

That being said ...
Since you are writing a game you want to use SND_ASYNC so that the program does not stop execution while the sound is playing. SND_SYNC halts execution and does not return until the sound has finished playing.

If you are using a file, you should be able to ditch the "new Sytem.ItrPtr()" and use something like ...

```
PlaySound(Application.StartupPath + [color=red]"Audio.wav"[/color], [b]0[/b], [color=teal]PlaySoundFlags[/color].SND_ASYNC)
```

As for using a resource, after you add the Lazer.Wav file to the resource directory, go into it's properties and try changing the "Build Action" to "Embedded Resource". 
I am not sure if that will work, as I cannot test it at the moment.

On another note, I think that this whole thing will break if you try to run it on Vista, which changed just about everything in the way audio is handled.


----------



## MrSeanKon (May 16, 2008)

Kreij said:


> Why are you calling unmanaged code (winmm.dll) from a managed C# application


 Cos I searched in Visual Studio 2008 help files and just I copied a part of  a code.
Beside of them thanks  I will go back to home later to check your ideas.


----------



## MrSeanKon (May 23, 2008)

Back:


```
try
{
   System.Media.SoundPlayer jh=new SoundPlayer(global::Preference.Properties.Resources.chimes);
   jh.Play();
}
catch
{
}
```
F_CK this code crashes sometimes (OK rare) and does not cause exception!!!

For this alternative solution I am not sure if it crashes cos I did not test it much (not enough free time):

```
Microsoft.VisualBasic.Devices.Audio jh=new Audio();
jh.Play(global::Preference.Properties.Resources.chimes,Microsoft.VisualBasic.AudioPlayMode.WaitToComplete);
```

Moreover the second code can add options (for the first not).
Of course we must add a new reference for Microsoft.VisualBasic.Devices in C#.


----------

