求用c语言编写的播放背景音乐的代码

快快!
2024-12-28 22:12:24
推荐回答(1个)
回答1:

#include
#include
#include
#include
#include

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 {
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 {
Beep(f[i],t[i]);
}
}