Wednesday, July 15, 2015

Creating Musical Tones with Beep

After I wrote just briefly about the Beep function in a previous post, I today want to examine in more detail the chosing of frequencies to output actual musical tones and prepare the playing of arbitrary melodies.
With Beep() characteristical Beep tones of a computer can be emitted (but over the speaker, if present), but frequency and duration can be set to any value. Because of this, although the sound is not the nicest, any arbitrary melody can be played with it. In this post I will show a formula for the calculation of tone frequencies, in the next one then build a little keyboard and then use a MIDI interface to enhance the sound and play guitar tabs.

On Wikipedia there is a nice overview over the tones created by a piano and the corresponding tone frequencies. The connection between piano key n (and with that tone) and frequency f can be expressed as follows:

f(n) = x(n-49)/12*440 Hz

In the following program the function PlayNote() outputs the tone belonging to the given tone via Beep(), also the duration is given (I added 24 to the key, which equals 2 octaves, because otherwise the beep is too low). In total the program plays the beautiful anthem of the United States of America.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Beep
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            PlayNote(20, 300);
            PlayNote(17, 170);

            PlayNote(13, 333);
            PlayNote(17, 333);
            PlayNote(20, 333);

            PlayNote(25, 666);
            PlayNote(29, 200);
            PlayNote(27, 130);

            PlayNote(25, 333);
            PlayNote(17, 333);
            PlayNote(19, 333);

            PlayNote(20, 666);
            PlayNote(20, 170);
            PlayNote(20, 170);

            PlayNote(29, 450);
            PlayNote(27, 220);
            PlayNote(25, 333);

            PlayNote(24, 666);
            PlayNote(22, 200);
            PlayNote(24, 100);

            PlayNote(25, 333);
            PlayNote(25, 333);
            PlayNote(20, 333);

            PlayNote(17, 333);
            PlayNote(13, 333);
        }

        public void PlayNote(int key, int duration)
        {
            key += 24;
            Console.Beep((int)(Math.Pow(Math.Pow(2, 1 / (double)12), key - 49) * 440), duration);
        }
    }
}
}

1 comment:

  1. So in the German post we got the German anthem, here the American one - would be cool if you guys could post other anthems as well!

    ReplyDelete