I\'m making an app for Mac OS X using Xcode, and I want it to play a alert sound when something happens.
What is the simplest code for playing a sound in Objective-C/Coc
To play audio on the Mac, you can either use NSSound for basic activities, or the more robust CoreAudio framework for more complicated tasks.
If you were to use NSSound
to achieve this goal, your code would look something like this:
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"replace-with-file-name" ofType:@"aif"];
NSSound *sound = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
// Do something with sound, like [sound play] and release.
OR
NSSound *sound = [NSSound soundNamed:@"replace-with-file-name-without-the-extension"];
// Do something with sound, like [sound play], but don't release (it's autoreleased).
If you were to use the second snippet, you would have to ensure that the sound file's extension is aiff
and not just aif
, since +soundNamed:
looks for very specific file extensions; I don't think aif
is on that list.
Using CoreAudio
is more complicated, so if you just want to play it and mess around with very simple settings, just use NSSound