sound(freq) 與 nosound() 是 Borland Turbo C 等舊編譯器提供的非標準函數,現代編譯器 (GCC, MSVC) 不支援。若在現代環境,請改用 Beep() (Windows API) 或跨平台音訊庫 (SDL_mixer, PortAudio)。
#define L1 262 // 低音 do
#define L2 294 // 低音 re
#define L3 330 // 低音 mi
#define L4 349 // 低音 fa
#define L5 392 // 低音 sol
#define L6 440 // 低音 la
#define L7 494 // 低音 si
#define N1 523 // 中音 do
#define N2 587 // 中音 re
#define N3 659 // 中音 mi
#define N4 698 // 中音 fa
#define N5 784 // 中音 sol
#define N6 880 // 中音 la
#define N7 988 // 中音 si
#define H1 1046 // 高音 do
// ... 依此類推
int melody[] = {
N3, N3, N4, N5, N5, N4, N3, N2, N1, N1, N2, N3, N3, N2, N2, 0, // 0 表休止
N3, N3, N4, N5, N5, N4, N3, N2, N1, N1, N2, N3, N2, N1, N1, 0
};
int duration[] = { 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 600, 300, 600, 600, /* ... */ };
#include <windows.h>
void play_note(int freq, int ms)
{
if (freq == 0) Sleep(ms);
else Beep(freq, ms);
}
int main()
{
for (int i = 0; i < sizeof(melody)/sizeof(int); i++)
play_note(melody[i], duration[i]);
return 0;
}