Playing Sounds with the Windows API and C#
Playing sounds in Visual Studio .NET’s managed environment is not a difficult task. It requires accessing an unmanaged Window’s multimedia library (winmm.dll), constructing a list of sound flags, and properly utilizing the PlaySound function.
To begin, let’s start a new C# project. By default, the project will load with the following .NET namespaces already listed:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
We need to add one more namespace, System.Runtime.InteropServices. This namespace is responsible for allowing managed code to access unmanaged resources. We add the namespace like any other:
using System.Runtime.InteropServices;
Having done so, we are now able to access winmm.dll, a Windows multimedia library that contains the function we need in order to play sound effects. We need two lines of code in order to properly access our PlaySound function. The first imports the .DLL file, and the second invokes the function so C# can utilize it. The code is as follows:
[DllImport(”winmm.dll”)]
private static extern bool PlaySound( string filename, int module, int flags );
…
Website: www.davidjsushil.com | Filesize: 100kb
No of Page(s): 3
Click here to download Playing Sounds with the Windows API and C#.
Related Tutorial
Tags: .NET, play sound, unmanaged code, win32 api, Windows API
Comments
Leave a Reply