#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
unsigned frequency[100];
char hight[100];
unsigned time[100];
unsigned rate;
void main()
{
void set(unsigned f[],char h[],unsigned t[],int r,int num);
void music(unsigned f[],unsigned t[],int num);
int flag=0;
FILE *f1;
int i,n,menu;
char FileName[30];
while(1)
{ f1=NULL;
i=n=0;
printf("本程序采用編碼的形式播放音樂。\n");
printf("\n用記事本編輯樂譜,然後通過輸入文件名播放音樂\n");
printf("樂譜文件可以自創,也可以抄別人的\n");
printf("\n現在可以先輸入數字再按回車播放音樂:\n");
printf("1 播放指定音樂music1\n");
printf("2 播放指定音樂music2\n");
printf("3 通過程序文件名播放音樂\n");
printf("4 退出\n");
while(1)
{
printf("menu=");scanf("%d",&menu);
if(menu==1)
{
strcpy(FileName,"music1.txt");
break;
}
if(menu==2)
{
strcpy(FileName,"music2.txt");
break;
}
if(menu==3)
{
scanf("%s",FileName);
break;
}
if(menu==4)
exit(0);
}
printf("\n該文件的音樂編碼如下:\n");
if((f1=fopen(FileName,"r"))==NULL)
{
printf("不能打開文件!\n");
exit(1);
}
fscanf(f1,"%d",&rate);
while(!feof(f1)&&flag!=1)
{
fscanf(f1," %d%c%d",&frequency[i],&hight[i],&time[i]);
printf(" %d%c%d",frequency[i],hight[i],time[i]);
if(time[i]!=-1)
{
i++;n++;
}
else
flag=1;
}
printf("\n");
set(frequency,hight,time,rate,n);
music(frequency,time,n);
fclose(f1);
}
getch();
}
void set(unsigned f[],char h[],unsigned t[],int r,int num)
{
int i,k;
for(i=0;i<num;i++)
{
t[i]=t[i]*r;
switch(h[i])
{
case 'H':k=4;break;
case 'M':k=2;break;
case 'L':k=1;
}
switch(f[i])
{
case 1: f[i]=262*k; break;
case 2: f[i]=296*k; break;
case 3: f[i]=330*k; break;
case 4: f[i]=349*k; break;
case 5: f[i]=392*k; break;
case 6: f[i]=440*k; break;
case 7: f[i]=494*k; break;
}
}
}
void music(unsigned f[],unsigned t[],int num)
{
int i;
for(i=0;i<num;i++)
{
Beep(f[i],t[i]);
}
}