开发者

How do I get NSSound to play a sound in a user-defined class?

This question is from an Objective-C newbie, so please bear with me. I'm trying to make sounds in my classes and have been successful using NSBeep() but not NSSound. Here is an example. Notice t开发者_运维技巧hat NSBeep(); and [[NSSound soundNamed:@"Frog"] play]; work fine in the "main.m" program, but only NSBeep(); works in the SoundMaker class. Any help in learning how to get NSSound to work is much appreciated.

main.m:

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import "SoundMaker.h"

int main() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSLog(@"This is the main program.");
    NSBeep(); // Works fine.
    sleep(1);
    [[NSSound soundNamed:@"Frog"] play]; // Works fine.
    sleep(1);
    [SoundMaker makeSound]; // Only NSBeep() works.

    [pool drain];
    return 0;
}

SoundMaker.h:

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>

@interface SoundMaker : NSObject
+(void) makeSound;
@end

SoundMaker.m:

#import "SoundMaker.h"

@implementation SoundMaker
+(void) makeSound
{
    NSLog(@"This is SoundMaker.");
    NSBeep(); // Works fine.
    sleep(1);
    [[NSSound soundNamed:@"Frog"] play]; // Doesn't work.
}
@end


So as noted, the solution is to add a sleep(...); statement following NSSound. Here is the change to SoundMaker.m that works:

#import "SoundMaker.h"

@implementation SoundMaker
+(void) makeSound
{
    NSLog(@"This is SoundMaker.");
    NSBeep(); // Works fine.
    sleep(1);
    [[NSSound soundNamed:@"Frog"] play]; // Works fine.
    sleep(1); // This added statement allows the preceding "play" message to work.
}
@end


In Xcode, if you set a breakpoint, does it get hit?

I have started only recently myself, so the +(void) looks weird to me; the book I am using only teaches

- (return_variable)methodname

[Edit]

I just tested it, added

- (void)playFrog;

To my interface.

I then implemented the function

- (void)playFrog
{
[[NSSound soundName:@"Frog"] play];
}

I called it from somewhere else in my application like

[self playFrog];

That worked.

[Edit 2]

After reading your code again, I noticed you didn't alloc/init your SoundMaker...

Try

SoundMaker *mySoundMaker = [[SoundMaker alloc] init];
[mySoundMaker makeSound];
[mySoundMaker release];


Most of the other answers, while okay, make it look more complicated than it needs to be. All you need is this statement (in Objective-C) wherever you want the sound to be produced:

[[NSSound soundNamed:@"Hero"] play];

You can find and test the various sound names in the Sound window of System Preferences.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜