make sounds (beep) with c++

前端 未结 12 638
暗喜
暗喜 2020-11-29 04:08

How to make the hardware beep sound with c++?

Thanks

相关标签:
12条回答
  • 2020-11-29 04:36

    You could use conditional compilation:

    #ifdef WINDOWS
    #include <Windows.h>
    void beep() {
      Beep(440, 1000);
    }
    #elif LINUX
    #include <stdio.h>
    void beep() {
      system("echo -e "\007" >/dev/tty10");
    }
    #else
    #include <stdio.h>
    void beep() {
      cout << "\a" << flush;
    }
    #endif
    
    0 讨论(0)
  • 2020-11-29 04:37

    The ASCII bell character might be what you are looking for. Number 7 in this table.

    0 讨论(0)
  • 2020-11-29 04:40

    I tried most things here, none worked on my Ubuntu VM.

    Here is a quick hack (credits goes here):

    #include <iostream>
    int main() {
      system("(speaker-test -t sine -f 1000)& pid=$!; sleep 1.0s; kill -9 $pid");
    }
    

    It will basically use system's speaker-test to produce the sound. This will not terminate quickly though, so the command runs it in background (the & part), then captures its process id (the pid=$1 part), sleeps for a certain amount that you can change (the sleep 1.0s part) and then it kills that process (the kill -9 $pid part).

    sine is the sound produced. You can change it to pink or to a wav file.

    0 讨论(0)
  • 2020-11-29 04:42

    There are a few OS-specific routines for beeping.

    • On a Unix-like OS, try the (n)curses beep() function. This is likely to be more portable than writing '\a' as others have suggested, although for most terminal emulators that will probably work.

    • In some *BSDs there is a PC speaker device. Reading the driver source, the SPKRTONE ioctl seems to correspond to the raw hardware interface, but there also seems to be a high-level language built around write()-ing strings to the driver, described in the manpage.

    • It looks like Linux has a similar driver (see this article for example; there is also some example code on this page if you scroll down a bit.).

    • In Windows there is a function called Beep().

    0 讨论(0)
  • 2020-11-29 04:44

    If you're using Windows OS then there is a function called Beep()

    #include <iostream> 
    #include <windows.h> // WinApi header 
    
    using namespace std;
    
    int main() 
    { 
        Beep(523,500); // 523 hertz (C5) for 500 milliseconds     
        cin.get(); // wait 
        return 0; 
    }
    

    Source: http://www.daniweb.com/forums/thread15252.html

    For Linux based OS there is:

    echo -e "\007" >/dev/tty10
    

    And if you do not wish to use Beep() in windows you can do:

    echo "^G"
    

    Source: http://www.frank-buss.de/beep/index.html

    0 讨论(0)
  • 2020-11-29 04:46

    alternatively in c or c++ after including stdio.h

    char d=(char)(7);
    printf("%c\n",d);
    

    (char)7 is called the bell character.

    0 讨论(0)
提交回复
热议问题