文号
t78346
阅读
4888
回复
2
收藏
2
【入门级程序】C语言电子琴
2015/12/23
IP:四川
这个比较简单。。。就用了一个Beep函数。。。
在DOS中发声是用sound函数,在Windows中可以用Beep函数,功能完全相同。
Beep(frequency, duration)函数可以在Windows中发出指定频率和时长的声音。
在WinXP下好像必须主板上有喇叭才能听到,在WinVista/7以后的系统中直接用声卡就行了。
#include <stdio.h>
#include <conio.h>
#include <windows.h>
     
// 音符频率
int tone_map[36][2] = {
    // 按住shift
    'O', 131, ')', 139, 'P', 147, '_', 156, '{', 165, '}', 175,
    // 常规音符
    '`', 185, '\t', 196, '1', 208, 'q', 220, '2', 233, 'w', 247,
    'e', 262, '4', 278, 'r', 295, '5', 313, 't', 332, 'y', 352,
    '7', 373, 'u', 395, '8', 418, 'i', 443, '9', 469, 'o', 497,
    'p', 524, '-', 555, '[', 588, '=', 623, ']', 660, '\\', 699,
    // 按住shift
    '!', 741, 'Q', 785, '@', 832, 'W', 881, '#', 993, 'E', 988,
};
     
// 相对时值
int time_map[16][2] = {
    // 支持 1/16 1/8 1/4 1/2 1
    'z', 1, 'x', 2, 'a', 3, 'c', 4,
    's', 5, 'd', 6, 'f', 7, 'v', 8,
    'g', 9, 'h', 10, 'j', 11, 'k', 12,
    'l', 13, ';', 14, '\'', 15, 'b', 16,
};
     
int base_time = 90; // 基准时值
int cur_time = 720; // 当前时值
     
int main()
{
     
    printf("base time (recommends 90): ");
    scanf("%d", &base_time);
    printf("tones: \n"
        "   )   _       `   1   2   |"
        "   4   5       7   8   9   |"
        "   -   =       !   @   #   \n"
        " O   P   {   }  tab  q   w |"
        " e   r   t   y   u   i   o |"
        " p   [   ]   \\   Q   W   E \n"
        );
    printf("durations: \n"
        "     a   s d f   g h j k l ; '\n"
        " z x   c       v               b\n"
        );
    printf("press shift-? to quit.\n");
    cur_time = base_time * 8;
    printf("\rduration = %d     ", cur_time);
    // 按键循环
    while (int ch = getch())
    {
        if (ch == '?') return 0; // 退出
        // 查表改变时值
        for (int j = 0; j < 16; j++)
            if (time_map[j][0] == ch)
            {
                cur_time = time_map[j][1] * base_time;
                printf("\rduration = %d     ", cur_time);
                goto cont;
            }
        // 查表发声
        for (int j = 0; j < 36; j++)
            if (tone_map[j][0] == ch)
                Beep(tone_map[j][1], cur_time);
    cont:
        
    }
    return 0;
}</windows.h></conio.h></stdio.h>
笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的