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
For example, add the AudioToolbox framework, the add the sound file to your resources / project, then add the below to your .h:
#import <AudioToolbox/AudioToolbox.h>
And then: (after @interface { blah } in your .h)
- (IBAction) playSound;
Add the following to your .m: (change 'Ping' and 'wav' to the respective file name and type)
- (IBAction) playSound
{
SystemSoundID soundID;
NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"Ping" ofType:@"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:soundFile], &soundID);
AudioServicesPlaySystemSound(soundID);
[soundFile release];
}
Basic playback of sound is quite easy.
You can use the NSSound class to load the file in a few different ways, for example, by name:
NSSound * myAwesomeSound = [NSSound soundNamed:@"AwesomeSound"];
This will need to be retained if you want to keep it around.
in this case the class will search certain particular directories, including your application bundle, for a sound file with that name. One important note is that the file must have the .aiff
(with two f's) extension in order to be found by this method.*
You would probably store the sound file in the Resources folder of your project; that's where "media" files are commonly kept.
Then you can play it very simply, perhaps using a button press:
- (IBAction)playTheSound:(id)sender {
NSSound * myAwesomeSound = [NSSound soundNamed:@"AwesomeSound"];
[myAwesomeSound play];
}
It's also possible to do some basic transport control: pausing, stopping, checking whether the sound has finished, and so on. Please see the Sound Programming Topics Guide for details.
*It's possible to use other formats, too, of course.
You can copy and add your .aif files to your project in Xcode as follows:
See Apple's examples & great info: here & here.
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