C ++蜂鸣声不起作用

C++ Beep not working

我是一名新手程序员,我正在尝试使用 Beep 函数用 C++ 制作一架钢琴。问题是,我在按键时听不到声音。这是我的代码:

#include <cstdlib>
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <conio.h>

using namespace std;

int main(){
    bool ciclo = true;
    char tecla = _getch();
    while (ciclo);
    if (tecla == 'd'){
        Beep(261, 100);
    }
    if (tecla == 'f'){
        Beep(293, 100);
    }
    if (tecla == 'g'){
        Beep(329, 100);
    }
    if (tecla == 'h'){
        Beep(349, 100);
    }
    if (tecla == 'j'){
        Beep(392, 100);
    }
    if (tecla == 'k'){
        Beep(440, 100);
    }
    if (tecla == 'l'){
        Beep(493, 100);
    }
    if (tecla == 'k'){
        Beep(523, 100);
    }

    if (tecla == 'q'){
        ciclo = false;
    };
    if (tecla == 'r'){
        Beep(277, 100);
    }
    if (tecla == 't'){
        Beep(312, 100);
    }
    if (tecla == 'u'){
        Beep(370, 100);
    }
    if (tecla == 'i'){
    Beep(415, 100);
    }
    if (tecla == 'o'){
        Beep(466, 100);
    }

}

我真的找不到任何错误,所以任何帮助将不胜感激。我正在 Visual Studio 2013 年编译。

可能你的电脑没有电脑音箱。查看文档:https://msdn.microsoft.com/en-us/library/windows/desktop/ms679277(v=vs.85).aspx

大多数现代 PC 都没有内置扬声器。

根据您的 include 语句,我可以看出您正在使用 Windows。 Windows 通常使用系统的默认消息声音(出现对话框时您听到的"ding")。确保您的扬声器已打开,或者尝试其他不使用 Beep 的解决方案。

虽然您的计算机确实可能没有这些内置扬声器。您的代码也陷入了无限循环。

while (ciclo);

我建议你循环,只要key不是q,这样用户就可以退出了。

这是您的代码工作的示例。

#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <conio.h>

using namespace std;

int main(){
    while (char tecla = _getch() != 'q')
    {
        if (tecla == 'd'){
            Beep(261, 100);
        }
        if (tecla == 'f'){
            Beep(293, 100);
        }
        if (tecla == 'g'){
            Beep(329, 100);
        }
        if (tecla == 'h'){
            Beep(349, 100);
        }
        if (tecla == 'j'){
            Beep(392, 100);
        }
        if (tecla == 'k'){
            Beep(440, 100);
        }
        if (tecla == 'l'){
            Beep(493, 100);
        }
        if (tecla == 'k'){
            Beep(523, 100);
        }
        if (tecla == 'r'){
            Beep(277, 100);
        }
        if (tecla == 't'){
            Beep(312, 100);
        }
        if (tecla == 'u'){
            Beep(370, 100);
        }
        if (tecla == 'i'){
        Beep(415, 100);
        }
        if (tecla == 'o'){
            Beep(466, 100);
        }
    }
}