Simple way to play a sound file (.aif)

后端 未结 4 1373
猫巷女王i
猫巷女王i 2021-02-02 17:45

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

4条回答
  •  甜味超标
    2021-02-02 18:29

    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.

提交回复
热议问题