Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » DirectX C# » Virtual Piano in C#

Virtual Piano in C#

In this application, the author shows you how to write a virtual piano using DirectDraw of DirectX 9.

Page Views : 76649
Downloads : 2928
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DotNetPiano.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Having finally got around to installing DirectX 9.0. I was impressed to find that it has several assemblies encapsulating .NET. Previous to the existence of .NET, I was loathe to touch those convoluted API's. The API's usually involved COM which sometimes requires a degree in Rocket Science or equivalent. Now perhaps its worth exploring.

This application takes advantage of DirectSound, one of the many media technologies packaged with DirectX 9. There are four steps to using the DirectSound technology in C#.

1. Create a sound device.  (Here we just use a default constructor for the default device.)

2.  Create a Buffer Description. The description contains information describing how the buffer will behave.

3.  Use the device, description, and the name of the .WAV file to create a secondary buffer. All sound is played using this buffer object.  You can also change properties of the secondary buffer (such as frequency) to alter the attributes of the sound

4. Play the sound.  Playing the sound is accomplished through a method on the secondary buffer.

Figure 1 - Dot Net Piano Application

The table below lists the classes in the Microsoft.DirectX.DirectSound assembly:

DirectSound Class Description

Device

The DirectSound Device
BufferDescription  The description object for the buffer that sets some of the properties of the buffer
SecondaryBuffer The buffer object where audio data is written to and played from.

Table 1 - DirectSound classes used in this project

In this article we use DirectSound in conjunction with GDI+ (instead of  DirectDraw) to create a virtual piano.  The piano only contains a little more than one octave, but you can easily extend it given the extensible design shown below:

Figure 2 - Virtual Piano UML Design reverse engineered using WithClass 2000

To play the piano in the program,  simply click the left mouse button on a virtual key on the keyboard.  You can also adjust the volume and panning of the piano with the sliding toolbars. 

This program uses DirectSound to take advantage of the fact that you can alter the frequency of the DirectSound buffer by changing the Frequency property.  In this way, you can use the same wave file for each key and simply alter the buffer's frequency for the particular key.  For this application, we chose the ding.wav file to produce the sound for the key, but the truth is, you could replace this file with any wave file of your choosing possessing a similar duration.

The first step is to put references in our project that allow us to use the DirectSound assemblies.  You can either use the DirectX 9 Visual C# Project Wizard that is automatically installed with DirectX 9 or you can manually insert the assemblies into your project.  You'll also need to declare the include references in your project as shown below:

using Microsoft.DirectX.DirectSound;
using Buffer = Microsoft.DirectX.DirectSound.Buffer;

The second step in playing sound is to create our Device object done in the form constructor shown in the code below.  The Device object is constructed with no parameters to obtain the default device.

Listing 1 - Creating the DirectSound Device

try
{
//Initialize the DirectSound Device
applicationDevice = new Device();
// Set the priority of the device with the rest of the operating system
applicationDevice.SetCooperativeLevel(this, CooperativeLevel.Priority);
}
catch(SoundException)
{
// could not create sound device, exit

MessageBox.Show("Could not initialize DirectSound. Sample will exit.", "Exiting...", MessageBoxButtons.OK,

MessageBoxIcon.Error);
Close();
return;
}

In the piano program, the sound is played each time a virtual piano key is pressed.  The code for the mouse being pressed is executed  in the mousedown event handler shown below.  This code determines the frequency of the Secondary Buffer by finding the key that was pressed and looking up the corresponding frequency for that piano key. (Each PianoKey object contains the frequency associated with it.).  Once the frequency is determined we simply need to play the WAV file with the new frequency.

Listing 3 - Handling the Playing of the Piano Key when the Mouse is Pressed

private
void PianoForm_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Determine the key that was pressed from the mouse position and lookup the frequency
int freq = FindFrequency(new Point(e.X, e.Y), out CurrentKey);
// Redraw the current key
if (CurrentKey != null)
Invalidate(CurrentKey.Border);
// Play the Note for the pressed key
PlayNote(freq);
}

The PlayNote method creates the secondary sound buffer,  assigns the frequency to the secondary sound buffer, and calls play on the buffer.  We need to recreate the buffer each time so we are always altering the original reference data.

Listing 4 - Play the Note Corresponding to the Frequency

private void PlayNote(int freq)
{
if (null != applicationBuffer)
{
// First we need to 'recreate' the buffer
// so we have a starting point with fresh data
applicationBuffer.Dispose();
applicationBuffer =
null;
// recreate a new buffer description as well
BufferDescription desc = new BufferDescription();
desc.ControlFrequency =
true;
desc.ControlPan =
true;
desc.ControlVolume =
true;
try
{
applicationBuffer =
new SecondaryBuffer(strFileName, desc, applicationDevice);
// Change the frequency here
applicationBuffer.Frequency = freq;
// No effects in this version
BufferPlayFlags PlayFlags = 0;
// Before we play, make sure we're using the correct settings of volume and pan
tbarPan_Scroll(tbarPan, null);
tbarVolume_Scroll(tbarVolume,
null);
// Play the contents of the buffer
applicationBuffer.Play(0, PlayFlags);
}
catch
{
}
}
}
 

Conclusion

Producing sound just became a lot easier because its encapsulated nicely in .NET.  This application could be easily expanded to turn the Virtual Piano into a virtual synthesizer because DirectSound gives you all sorts of effects that you can use to alter your wave file.  We'll save this for the next composition using C# and .NET.

References

Microsoft DirectX on MSDN

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, Merrill Lynch. Currently he is a senior consultant at JP Morgan Bank. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@microgold.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Mindcracker MVP Summit 2012
Become a Sponsor
 Comments
Didn't work for me by Michael On November 25, 2006

Mike,

 

Great app.  Exactly what I was looking for.  This will really help with my learning.  Thanks!!

But no sound is comming out for me.  And the values on the form don't change for me when I adjust the sliders.  Any idea what is going on?

I have the newest version of VC#Express and 2006DirectX9.0.  My system converted the file when I unzipped it.  I even hard coded the values for the text and integer values, but no luck.

Thanks,

Mike

Reply | Email | Modify 
Re: Didn't work for me by Jens On February 27, 2007

Works fine here.

You have to place ding.wav from the bin\Debug to c:\ding.wav  or change the path in PianoForm.cs line 25, to the path of the ding.wav.

Reply | Email | Modify 
Thanks by Bishoy On July 22, 2007
That's exactly what i was looking for thank u very much
Reply | Email | Modify 
LoaderLock error when debugging in VS2005/2008 by Norbert On February 17, 2008
Managed Debugging Assistant 'LoaderLock' has detected a problem in... What to do to get rid of this error (I mean: which parts of the code)?
Reply | Email | Modify 
Re: LoaderLock error when debugging in VS2005/2008 by Sam On March 16, 2011
LoaderLock is a common problem for DirectX. It is essentially a warning from the debugger. The warning can be turned off and there is usually no problem after that.
Reply | Email | Modify 
Virtual Pitch Pipe by j On April 3, 2009
This is another version that doens't require directx installed on the machine: http://code.msdn.microsoft.com/virtualpitchpipe/
Reply | Email | Modify 
Nice by Amal On August 5, 2010
Nice product
Reply | Email | Modify 
Invalid application by Sam On March 16, 2011
I built the project using VS 2010 and when I execute it it says the image is not a valid Win32 application. I am currently exploring and don't really need this but if I did need it I would try creating a new project and migrating the source files etc. over but I just wanted to post this in case it helps.
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.