Posts Tagged ‘ beginner ’

Console.Beep for 64-bit Windows

Lately, I’ve been experimenting with making music with computers. I do not have a music background so it’s been a difficult route. One of the things I regret is not taking a music or band class in high school. Fortunately, there are plenty of websites that explain how to read sheet music and plenty of videos to watch to learn how to play popular songs. It’s like learning a new programming language in which you’re learning new syntax and semantics, but takes a lot of practice and constant self-improvement via experimentation and feedback from others to perfect.

Now you’re probably thinking why I’m talking about music theory on a programming blog. Well, a cheap and easy way to make music is to write a console application using Visual C# Express. You can use Console.Beep() and specify a frequency and duration to make a note. This is the route I tried, but I was extremely disappointed to find out that Console.Beep() didn’t work with the 64-bit version of Windows starting with Vista and newer.

Well, there is a work-around! This MSDN forum post outlines how to send the beep to the computer speakers via a class. It appears to take the note information (amplitude, frequency, and duration), convert it into a sine wave, converts the sine wave to a byte array, saves the byte array as a WAV file in memory, and plays the WAV file to the computer speakers. Brilliant!

I am not the author of the code so any questions regarding it should be posted in the forum post, but I will repost the code here in case the forum post disappears.

// include these at the top of the file:
// using System;
// using System.IO;
// using System.Media;

// the following code goes inside your namespace
public class Beep
{
    // I added this function because amplitude should just always be 1000
    // < 1000 sounds muffled and > 1000 throws an exception
    public static void Play( double frequency, double duration )
    {
        BeepBeep( 1000, frequency, duration );
    }

    private static void BeepBeep( double Amplitude, double Frequency, double Duration )
    {
        double Amp = ( ( Amplitude * ( System.Math.Pow( 2, 15 ) ) ) / 1000 ) - 1;
        double DeltaFT = 2 * Math.PI * Frequency / 44100.0;

        int Samples = (int)(441.0 * Duration / 10.0);
        int Bytes = Samples * sizeof(int);
        int[] Hdr = { 0X46464952, 36 + Bytes, 0X45564157, 0X20746D66, 16, 0X20001, 44100, 176400, 0X100004, 0X61746164, Bytes };

        using ( MemoryStream MS = new MemoryStream( 44 + Bytes ) )
        {
            using ( BinaryWriter BW = new BinaryWriter( MS ) )
            {
                for ( int I = 0; I < Hdr.Length; I++ )
                {
                    BW.Write( Hdr[I] );
                }
                for ( int T = 0; T < Samples; T++ )
                {
                    short Sample = System.Convert.ToInt16( Amp * Math.Sin( DeltaFT * T ) );
                    BW.Write( Sample );
                    BW.Write( Sample );
                }

                BW.Flush();
                MS.Seek( 0, SeekOrigin.Begin );
                using ( SoundPlayer SP = new SoundPlayer( MS ) )
                {
                    SP.PlaySync();
                }
            }
        }
    }
}

Enumeration and arrays

Recently, I discovered the usefulness of the enum type in C++. I can’t believe how long I’ve gone without using an enum because I didn’t know why I should use it over a #define. The two main reasons to use enums over #define is 1) sequential self-numbering and 2) enums allow the value to be visible to the debugger. This post is about the first reason.

Let’s say we want a list of variables, and the variables need to be assigned a unique number for processing, but we don’t care what number is assigned to it. Enumeration to the rescue! Define an enum with a list of variables and it will assign each variable an integer value starting from zero. For example:

enum
{
    alpha,
    beta,
    delta,
    gamma
};

// The values stored in the enum variables are:
// alpha == 0
// beta == 1
// delta == 2
// gamma == 3

Now you can add another variable to the the list in any position (because remember we don’t care what number is assigned to it, it just has to be a unique number) and you won’t have to renumber the other values. It just does it automatically!

enum
{
    alpha,
    beta,
    omega, //<---------
    delta,
    gamma
};

// The values stored in the enum variables are:
// alpha == 0
// beta == 1
// omega == 2
// delta == 3
// gamma == 4

You’re probably thinking: “Great, it self-numbers. What’s the point?” Well the point is that you can use this as array indices and declarations. Assume you have some boolean option settings for your program with the following options: isFullScreen, isWidescreen, isMoving.

Let’s start out making a new file called “options.h” with the following code:

namespace options
{
    enum
    {
        isFullScreen,
        isWidescreen,
        isMoving,
        size
    };
}

I put the enum inside a namespace so that I can use the enum in multiple places without creating an instance of an object. The namespace also allows Visual Studio to list all the enum variables in the autocomplete dialog when using the scope operator ("::"). All I need to do is add #include "options.h" to the top of the header files where I want to use this enum. The last variable size is always going to be the size of the array. Now, remember an enum variable is a const integer value which is why we can use it as an array index value. To use this enum in a class I would use the following code snippet:

// include the namespace file
#include "options.h"

// declares the array, but does not initialize the elements
bool myOptions[options::size];

// then I can initialize the values like so:
myOptions[options::isFullScreen] = false;
myOptions[options::isWidescreen] = false;
myOptions[options::isMoving] = false;

...

// usage example
if(myOptions[options::isFullScreen])
{
    // do something
}

That’s fine and dandy, but if we add another option, we would have to add another line to set that option to false on initialization. We’re lazy and are willing to write more code now to prevent having to write more code in the future so let’s add a reset function to the options namespace.

namespace options
{
    enum
    {
        isFullScreen,
        isWidescreen,
        isMoving,
        size
    };

    static void Reset(bool myArray[options::size], bool value);
}

// the following lines of code are in the same file as the namespace
/**
@brief Resets all the options to a specific value
@param myArray  The array of options using the namespace's enum
@param value    The value to assign to all the options
*/
void options::Reset(bool myArray[options::size], bool value)
{
    for(int i=0; i<options::size; i++)
    {
        myArray[i] = value;
    }
}

I put a value as a parameter because I want the flexibility to set all the options to true or false. The static keyword allows us to use the function without declaring an object so we just reference the function like so in the class:

// declares the array, but does not initialize the elements
bool myOptions[options::size];

// resets all the options
options::Reset(myOptions, false);

...

// usage example
if(myOptions[options::isFullScreen])
{
    // do something
}

Now let’s add another option to the enum to detect if a file is loaded:

namespace options
{
    enum
    {
        isLoaded, //<-----------
        isFullScreen,
        isWidescreen,
        isMoving,
        size
    };

    static void Reset(bool myArray[options::size], bool value);
}

The beauty of this is I can add this function without having to renumber or edit the existing code! I just add the new option where I need to use it.

// still works correctly
if(myOptions[options::isFullScreen])
{
    // do something
}

// do this for the new option
if(myOptions[options::isLoaded])
{
    // do something
}

This is not the only example for using enums with arrays. There are so many possibilities such as having an array of strings and looping through it to read the values. Learning how to use enums for arrays changed my life. It has made me more productive and made maintenance so much easier. It’s such an elegant, cheap, and easy way to improve the code tenfold.

Formatting and Styling Strings (C#)

We’ve discussed different ways to format a string using printf for C++ and string.format for Java/Android and since I’ve been working with C# recently I would add that to the blog as well.

In C#, it’s just like Java/Android: use string.Format(). Instead of dollar signs, you would use curly brackets with the parameter number. What’s nice is that you don’t really need to worry about the type. For example:

int foo = 9000;
string bar = "sparta";

string fubar = string.Format("This is {0}! It is over {1}!", bar, foo);

Would result with:

This is sparta! It is over 9000!"

See how I didn’t need to tell it {0} was a string and {1} was an integer? You can also add the format inside the curly bracket if you wish such as:

{index,length:formatString}

Where index is the index of the value to use; length is the amount of spaces you want this variable to take up; and formatString is a standard or custom string that can be used to do more formatting (such as setting up a date in US or EU format).

As usual, if you’d like to know more about the details, visit MSDN for more reading.

Want to learn C#?

I’ve been wanting to learn C# for a while so I finally started learning it a few weeks ago. I lightly touched C# back in the fall of 2009. We had a quick crash course trying to get a XNA game working thinking that was the best way to make a game in two weeks. That was a very terrible learning situation and I haven’t thought much about C# since then. Once I decided to take a shot at it again, I was definitely a lot wiser than I was 1.5 years ago. Now that I’ve got some good C++ programming, MFC UI development, and Visual Studio usage skills down, jumping into C# was not as hard as it was when I first came across it. Actually, working with C# in Visual Studio is so much easier than C++ and MFC that I feel like I’ve been converted to a new religion. Seriously, how did I live without this all my programming life?! String conversions, getting file paths/names/extensions, and capturing events are just one call away instead of some hackjob conversion and string parsing! C++ and MFC is like driving a Volvo 240: solid, reliable, and old, but hard to work on and possibly relies on hackjob repairs to make things work. C# with .NET is like a brand new Volvo S60: new, easy to use (from the driver’s seat), and safe with all the electro-nannies, but it’s a lot more complicated under the hood, but you’re not likely to go that deep anyways. I followed the tutorial at Home and Learn and got a nice primer on C#. The tutorials are very easy to read and understand so I recommend checking it out if you’re a beginner. It’s nice that Microsoft offers Visual Studio Express for free to play around with also. Get Visual Studio Express and start making some programs!

Be Kind, Please Find

Be Kind, Please Find is the first graphical program that Kevin and I worked on together. It paved the way to making more visually impressive software and eventually Android development. In the spring of 2008, we took a game development class after finishing our basic C++ programming classes in college. We did not think much of it at the time as we thought as the class was just going to be an easy way to get a minor and bump up our GPA, but that semester was the first step towards our future. The project taught us how to manage resources and tasks to ensure that important things got done. It also taught us the importance of creating a good demo and presentation as that is what hooks people in. Our college senior project mirrors the philosophy and spirit of this project which set the bar for future students. It is our honor and privilege to present Be Kind, Please Find to the world.

Be Kind, Please Find
http://bekind.phamous-apps.com/

Learn how to code!

LifeHacker recently did a series on the basics of programming. In their articles, they are using JavaScript which is very easy to use and you don’t need to download any SDK or compiler. Just open up your favorite text editor and do your code, then save and view the results in your favorite web browser. Here are the links in case you missed it:

Part 1: Variables and Datatypes
Part 2: Working with Variables
Part 3: Arrays and Logic Statements
Part 4: Understanding Functions and Making a Guessing Game
Part 5: Learn to Code Epilogue: Best Practices and Additional Resources

Formatting and Styling Strings (C/C++)

So, talking about formatting and styling strings for Java/Android has got me thinking about formatting and styling strings for C/C++. For C/C++, we use printf and sprintf. Both printf and sprintf work exactly the same except sprintf puts the output to a character array and printf puts the output to standard output (such as the console/terminal).

If you just want to put a line out to standard output, you’d write something like this:

printf("Hello World!\n");

If you want to output strings and numbers, you’d use it like this:

float freqMHz = 100.2578;
printf("%-30s: %5.2f MHz\n", "Frequency", freqMHz);

The previous example is a bit more advanced, but that’s probably as advanced as it gets. %-30s means the first parameter is a string (the “s”) and we want to allot 30 spaces for the string and left align it (the “-“). The %5.2f means the second parameter is a float and we want to format it such that we want 5 digits for the integer part with a 2 digit precision for the decimal part. The string sent to standard output would be as follows:

Frequency:                    100.26 MHz

Note that the float gets rounded up when it is formatted. For sprintf, the syntax is the same, except we add a character array to the parameters. The character array is where we would save the final string. For example, the following code will output the exact same thing as the above example:

char* outputStr = new char[1024];
sprintf(outputStr, "%-30s: %5.2f MHz\n", "Frequency", freqMHz);
printf(outputStr);

The cool thing about printf and sprintf is that you can add as many parameters as you want to the formatted string. The useful thing about printf and sprintf is that you can mix and match data types (like in the previous examples) without having to do typecasting or using (with cout) to get it to look nice. You can even format numbers to hexadecimal or scientific notation! Pretty slick, right?

Also, remember to add a newline character (“\n”) to the end of the string. It will run the next printf on the same line as the previous printf if you don’t.

Anyways, for all the different flags you can use to format printf and sprintf, check out the documentation at cplusplus.com.