C++用Beep函数来弹钢琴
1 #include<windows.h> 2 #include<iostream> 3 #include<string> 4 using namespace std; 5 int stop=500; 6 int getFreq(char key){ 7 int freq=0; 8 switch(key){ 9 //中音区 10 case ‘a‘:freq=262;break; 11 case ‘s‘:freq=294;break; 12 case ‘d‘:freq=330;break; 13 case ‘f‘:freq=349;break; 14 case ‘g‘:freq=392;break; 15 case ‘h‘:freq=440;break; 16 case ‘j‘:freq=494;break; 17 //低音区 18 case ‘z‘:freq=131;break; 19 case ‘x‘:freq=147;break; 20 case ‘c‘:freq=165;break; 21 case ‘v‘:freq=175;break; 22 case ‘b‘:freq=195;break; 23 case ‘n‘:freq=220;break; 24 case ‘m‘:freq=247;break; 25 } 26 return freq; 27 } 28 string twoTiger="asdaasdadfg dfg g_h_g_f_dag_h_g_f_dasba sba"; 29 string aiHe="asddghhaadsaasd asddghhaadsaama"; 30 int main(){ 31 string score=aiHe; 32 33 for(int i=0;i<score.length();i++){ 34 if(score[i]==‘ ‘){ 35 Sleep(stop);//四分休止符 36 }else if(score[i]==‘_‘){ 37 //do nothing 38 }else{ 39 if((i+1)==score.length()){//是否到末尾 40 Beep(getFreq(score[i]),stop); 41 }else{ 42 if(score[i+1]==‘_‘){//是否是八分音符 43 Beep(getFreq(score[i]),stop/2); 44 }else{ 45 Beep(getFreq(score[i]),stop);//四分音符 46 } 47 } 48 49 } 50 } 51 return 0; 52 }