Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trigger sound alert in OSX using Cocoa?

Tags:

cocoa

osx-lion

When Finder finishes copying of files then it triggers a sound alert. How can I do that from my app?

Please note that it is not the same as simply playing a sound. I am from Windows background so I am assuming that OSX allows users to configure notification sound from some central location. So, if the user chooses a different sound for an event then that API should play that new sound. This way I can make my app gel into the system and it will be able to alert the user using sound which the user is familiar with.

like image 738
AppleGrew Avatar asked Feb 06 '12 09:02

AppleGrew


1 Answers

Answering my own question.

  • Found a good guide on this - System Sounds in Cocoa (wayback machine archive).
  • Official guide - Introduction to Sound Programming Topics for Cocoa.
  • Official NSSound reference.

Update

Additional notes

The system alerts are the ones which user can configure, others like emptying recycle bin, sound made when copying files are not.

NSBeep is the simplest way to trigger the alert sound which notifies the user of an error. Other sounds are available at the following locations in Lion.

  • /System/Library/Components/CoreAudio.component/Contents/SharedSupport/SystemSounds
  • For other user interface sounds check the Resources folder under related packages of the core applications. These application packages can be found in /System/Library/CoreServices/.

So, for example if you want to play the move to recycle bin sound then use the following code.

NSSound *systemSound = [[NSSound alloc] initWithContentsOfFile:@"/System/Library/Components/CoreAudio.component/Contents/SharedSupport/SystemSounds/dock/drag to trash.aif" byReference:YES];
if (systemSound) {
    [systemSound play];
}

Caveats

The name and path of the sound files may change at anytime. In fact the location of SystemSounds before Lion was /System/Library/Components/CoreAudio.component/Contents/Resources/SystemSounds.

like image 171
AppleGrew Avatar answered Sep 30 '22 06:09

AppleGrew