C#用编程弹琴,电子音乐的节奏,走起!
写一个程序,让计算机弹琴。
Beep可以发声。
程序里面使用了enum数据类型,
定义了声音的频率
定义了声音持续时间
这样就形成了旋律。
using System;
using System.Threading;
namespace Ear
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//for(int i=0;i<5;i++)
// Console.Beep();
Console.Write(Tone.A);
Note[] Mary=
{new Note(Tone.B,Duration.QUARTER),
new Note(Tone.A,Duration.QUARTER),
new Note(Tone.GbelowC,Duration.QUARTER),
new Note(Tone.A,Duration.QUARTER),
new Note(Tone.B,Duration.QUARTER),
new Note(Tone.B,Duration.QUARTER),
new Note(Tone.B,Duration.HALF),
new Note(Tone.A,Duration.QUARTER),
new Note(Tone.A,Duration.QUARTER),
new Note(Tone.A,Duration.HALF),
new Note(Tone.B,Duration.QUARTER),
new Note(Tone.D,Duration.QUARTER),
new Note(Tone.D,Duration.HALF),
};
for(int i=0;i<6;i++)
Play(Mary);
}
protected static void Play(Note[]tune){
foreach(Note n in tune){
if(n.NoteTone==Tone.REST)//枚举的比较
Thread.Sleep((int)n.NoteDuration);//枚举转成int
else
Console.Beep((int)n.NoteTone,(int)n.NoteDuration);
}
}
protected enum Tone
{
REST=0,
GbelowC=196,
A=220,
Asharp=233,
B=247,
C=262,
Csharp=277,
D=294,
Dsharp=311,
E=330,
F=349,
Fsharp=370,
G=392,
Gsharp=415,
}
protected enum Duration
{
WHOLE=1600,
HALF=WHOLE/2,
QUARTER=HALF/2,
EIGHTH=QUARTER/2,
SIXTEENTH=EIGHTH/2,
}
protected struct Note
{
Tone toneVal;
Duration durVal;
public Note(Tone freq,Duration time){
toneVal=freq;
durVal=time;
}
public Tone NoteTone{get{return toneVal;}}
public Duration NoteDuration{get{return durVal;}}
}
}//end class
}
参考