jump to navigation

PlaySound: A Better Way to Play Wav Files in C# April 30, 2010

Posted by codinglifestyle in C#, CodeProject, Uncategorized.
Tags: , , , , ,
trackback

The other day I was whipping up a fun utility which played some wav files.  I was giving this to people who’s desktop us Windows Server 2008 so using the Windows Media Player COM object wasn’t an option and SoundPlayer didn’t seem to work with any of the wav files I had for some reason.

Back in my C++ days I used to do this all the time with winmm.dll’s PlaySound (and have a piece of freeware which uses this to a great extent).

Well, once again as a C# programmer I am saved by pinvoke!

public static class Wav

{

[DllImport(“winmm.dll”, SetLastError = true)]

static extern bool PlaySound(string pszSound, UIntPtr hmod, uint fdwSound);

[Flags]

public enum SoundFlags

{

/// <summary>play synchronously (default)</summary>

SND_SYNC = 0x0000,

/// <summary>play asynchronously</summary>

SND_ASYNC = 0x0001,

/// <summary>silence (!default) if sound not found</summary>

SND_NODEFAULT = 0x0002,

/// <summary>pszSound points to a memory file</summary>

SND_MEMORY = 0x0004,

/// <summary>loop the sound until next sndPlaySound</summary>

SND_LOOP = 0x0008,

/// <summary>don’t stop any currently playing sound</summary>

SND_NOSTOP = 0x0010,

/// <summary>Stop Playing Wave</summary>

SND_PURGE = 0x40,

/// <summary>don’t wait if the driver is busy</summary>

SND_NOWAIT = 0x00002000,

/// <summary>name is a registry alias</summary>

SND_ALIAS = 0x00010000,

/// <summary>alias is a predefined id</summary>

SND_ALIAS_ID = 0x00110000,

/// <summary>name is file name</summary>

SND_FILENAME = 0x00020000,

/// <summary>name is resource name or atom</summary>

SND_RESOURCE = 0x00040004

}

public static void Play(string strFileName)

{

PlaySound(strFileName, UIntPtr.Zero, (uint)(SoundFlags.SND_FILENAME | SoundFlags.SND_ASYNC));

}

}

Example:

FileInfo fi = new FileInfo(sFile);

Wav.Play(fi.FullName);

Advertisement

Comments»

1. PlaySound: A Better Way to Play Wav Files in C# « Coding Lifestyle | Source code bank - April 30, 2010

[…] posted here: PlaySound: A Better Way to Play Wav Files in C# « Coding Lifestyle If you enjoyed this article please consider sharing […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: