开发者

Is there a way to play a system beep on Mac OS?

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 th开发者_如何学运维e Mac and Windows platforms?


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.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜