Another small task to play a beep or tones (waveform audio) by using C# or C++. I found there are a few ways to do that according to MSDN. I did two examples:
- Using .NET class SoundPlayer. The key point is to use PlaySync() method to play the sound instead of Play() because the latter plays sound asynchronously (by starting another thread) then you may not hear the sound when the program is ended. The sound file is embedded. In order to read the sound file from resource folder, you need to be careful with the path to the sound file (GetManifestResourceStream needs it as a parameter). You may also use ResourceManager class to achieve the same purpose.
- Using Win32 APIs, such as WAVEFORMATEX, waveOutOpen, waveOutPrepareHeader, waveOutWrite, etc. Here is a detailed tutorial on how to use those functions. The difficult part is to find out the wave generation mathematic expressions for different sound waves. Here is another tutorial on how to do that. Also you can use a tool called ETG to get such expressions (of course you have to modify them, not sure how to create delays as demonstrated in the tool).
You may use DirectX to implement the function. Here is a simple example with just a few lines of code.
Some tips:
- In C# or VB.NET, to use Win32 API, you need to import dlls, for example:
[DllImport("CoreDll.DLL", EntryPoint="PlaySound", SetLastError=true)]
private extern static int WCE_PlaySound(string szSound, IntPtr hMod, int flags); - In Visual Studio IDE, debug (System.Diagnostics) outputs normally go to Immediate Window (you can type ‘immed’ to bring Immediate Window). You may also redirect the contents in Output Window to Immeidate Window by changing VS options.
- How to handle problems between TCHAR and std::string can be found in this blog. Generally speaking, define a tstring type in your C head file:
#ifdef _UNICODE
#define tstring wstring
#else
#define tstring string
#endif - Here is a good reference on how to use std::string functions.