首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言問答

C語言使用 sound() 函數播放歡樂頌主旋律

     編輯:C 語言問答

DOS/Windows 主控台下的簡易音樂播放

sound(freq) 與 nosound() 是 Borland Turbo C 等舊編譯器提供的非標準函數,現代編譯器 (GCC, MSVC) 不支援。若在現代環境,請改用 Beep() (Windows API) 或跨平台音訊庫 (SDL_mixer, PortAudio)。

音頻定義 (Hz)

#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
// ... 依此類推

歡樂頌旋律陣列 (簡譜 3=mi)

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, /* ... */ };

Windows 版播放範例

#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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved