[C# .NET] System.Media VS. PlaySound.


NEW System.Media in .NET Framework 2 Vs. PlaySound.

Is very common idea to insert some sounds in your application like beep, wrong messages, etc...

In .NET Framework 2.0 has been added new namespace: System.Media.
Using it you can simply play very common system sounds like in this example:


using System.Media;
...
...
//For Question.
SystemSounds.Question.Play();

//For Beep.
SystemSounds.Beep.Play();

//etc...



However, if your application don\'t have others new features of .NET 2.0 Framework you can run it under old .NET Env. but you lose the sounds! So, you can continue to use PlaySound method like this example:


using System.Runtime.InteropServices;
...
//Reference external method.
[DllImport(\"winmm.DLL\", EntryPoint = \"PlaySound\", SetLastError = true)]
private static extern bool PlaySound(string szSound, System.IntPtr hMod, PlaySoundFlags flags);

//Define Flags.
[Flags]
public enum PlaySoundFlags : int
{
SND_SYNC = 0x0000,
SND_ASYNC = 0x0001,
SND_NODEFAULT = 0x0002,
SND_LOOP = 0x0008,
SND_NOSTOP = 0x0010,
SND_NOWAIT = 0x00002000,
SND_FILENAME = 0x00020000,
SND_RESOURCE = 0x00040004
}

//Wrap external method in to your method definition.
private void playSound()
{
try { PlaySound(\"SOUND_PATH\", new System.IntPtr(), PlaySoundFlags.SND_SYNC); }

catch { }
}


In some cases you must need to play sound in asynchronous way. You can use what I call a \"Threaded Method\". Threaded Method is a simple delegate started by a Thread. You can play asynchronous sound in this way:


using System.Threading;
...
...
//Define new Thread.
private Thread Sound_Thread;

...

//Define ThreadStart.
Sound_Thread = new Thread(new ThreadStart(this.playSound));

//Define method that call my Sound_Thread.
//In this case the method is a Form event like button click!
private void Button_Click(object sender, EventArgs e)
{
Sound_Thread.Start();
}


---
Enjoy your Sounds! :)


Article published on: Dario Maggiari Blog - NecroBlog - http://necrosoft.altervista.org/NecroBlog/
Reference URL: http://necrosoft.altervista.org/NecroBlog//index.php?mod=read&id=1150389380