Think about it, how do you implement those nice notes in the program? Isn’t this very interesting? If we can make a small program to simulate the pronunciation of seven notes in music, can you do it?
Next, let’s take a look at the source of this magical sound. . .
First, we build a console project. The core of this program is how to make the system pronounce sounds. This uses the Beep() method in the Console class. It has two parameters. The first is to control the frequency of the sound, and the second is to control the time. length.
Another method is ReadKey(), which reads one character each time. It has a bool parameter to control whether the pressed key is displayed in the console window.
What’s more interesting is that we can also record the input notes to record the music we just played. Here, we use the timespan type to calculate the time interval, and also use the thread pause (Thread.Sheep).
Below is the code of the entire program for reference.
/// <summary> /// 获取声音及改变背景颜色 /// </summary> /// <param name="i"></param> static void Sound(int i) { int fre=(Convert.ToInt32(i) + 13) * 37; switch (i) { case '1': Console.Beep(fre, 300);//第一个参数指定声音的频率,第二个参数指定声音的持续时间 Console.BackgroundColor = ConsoleColor.Blue; Console.Clear(); break; case '2': Console.Beep(fre, 300); Console.BackgroundColor = ConsoleColor.Cyan; Console.Clear(); break; case '3': Console.Beep(fre, 300); Console.BackgroundColor = ConsoleColor.Green; Console.Clear(); break; case '4': Console.Beep(fre, 300); Console.BackgroundColor = ConsoleColor.Red; Console.Clear(); break; case '5': Console.Beep(fre, 300); Console.BackgroundColor = ConsoleColor.Yellow; Console.Clear(); break; case '6': Console.Beep(fre, 300); Console.BackgroundColor = ConsoleColor.White; Console.Clear(); break; case '7': Console.Beep(fre, 300); Console.BackgroundColor = ConsoleColor.Blue; Console.Clear(); break; default: break; } } //该类定义记录输入的字符以及时间间隔 class LL { public char c;//字符 public DateTime d;//时间间隔 } static void Main(string[] args) { Console.SetWindowSize(100,30); List<LL> record = new List<LL>(); while (true) { ConsoleKeyInfo cki = Console.ReadKey(true); char i = cki.KeyChar; if (i != 'q')//如果输入q,则开始按录制的播放 { LL l = new LL(); l.c = i; l.d = DateTime.Now; record.Add(l); Sound(i); } else { for (int k = 0; k < record.Count;k++ ) { TimeSpan tspan; if (k != 0)//如果是第一个,则计算时间间隔 { tspan=record[k].d - record[k-1].d;//计算输入的时间间隔 Console.WriteLine(tspan); Thread.Sleep(tspan);//将当前线程阻塞指定的时间。 } Sound(record[k].c); } record.Clear();//将记录清空 } } }
The above is the detailed content of Share the piano pronunciation applet in the console. For more information, please follow other related articles on the PHP Chinese website!