5

Is there a way to play a system beep on Mac OS using C++ and Xcode? I understand that I need to use a library. Is there a library that works across both the Mac and Windows platforms?

Mat
  • 202,337
  • 40
  • 393
  • 406
Moshe
  • 57,511
  • 78
  • 272
  • 425

3 Answers3

6

I think you probably want to use NSBeep


NSBeep

Plays the system beep.

#include <AppKit/AppKit.h>

void NSBeep (void);

This seems to work OK for a command line tool:

#include <AppKit/AppKit.h>
#include <iostream>

using namespace std;

int main(void)
{
    cout << "Hello world !" << endl;
    NSBeep();
    sleep(1)
    return 0;
}

$ g++ -Wall -framework AppKit beep.cpp -o beep
$ ./beep

Update May 2021

While this solution worked in 2011, it seems that AppKit is now no longer C++-compatible, so you now need to treat the file as Objective-C++, i.e. rename beep.cpp to beep.mm.

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • In using C++ and not Foundation. – Moshe Sep 13 '11 at 21:37
  • Do you mean you're just writing a command line tool rather than a proper Mac OS X application ? You can still use NSBeep() - see above example. – Paul R Sep 13 '11 at 21:44
  • This doesn't compiles – 김선달 May 22 '21 at 09:57
  • @김선달: you're right - it ceratainly worked 10 years ago, when I wrote this answer, but evidently something got broken in the mean time. It doesn't look like you can use the AppKit framework with C++ any more. – Paul R May 22 '21 at 14:13
  • @김선달: I found that you can still compile the above code as is, but for current versions of macOS and Xcode the source file needs to be treated as Objective-C++ rather than C++ (change .cpp extension to .mm). – Paul R May 22 '21 at 20:37
  • @PaulR Thanks for the additional information. That's sad btw... – 김선달 May 23 '21 at 04:48
2

Here is an alternate method which works on current macOS (Big Sur) in 2021 (unlike my earlier NSBeep solution, which now only works with Objective-C++, and not with vanilla C++). I disassembled NSBeep and found that it just calls AudioServicesPlayAlertSound with a parameter value 0x1000 (kSystemSoundID_UserPreferredAlert). AudioServicesPlayAlertSound is part of the AudioToolbpx framework, which fortunately still works with C++ (unlike AppKit).

#include <AudioToolbox/AudioServices.h>
#include <iostream>

using namespace std;

int main(void)
{
    cout << "Hello world !" << endl;
    AudioServicesPlayAlertSound(kSystemSoundID_UserPreferredAlert);
    sleep(1);
    return 0;
}

Compile and run:

$ g++ -Wall -framework AudioToolbox beep.cpp -o beep
$ ./beep
Paul R
  • 208,748
  • 37
  • 389
  • 560
2

The cross platform way to play a beep is std::cout << "\007";. I had been trying to play it by passing in a char and then decrementing until 7. That didn't work. Explicitly outputting the code did work though.

Moshe
  • 57,511
  • 78
  • 272
  • 425