Developer
Developer

Reputation: 404

Playing NSSound in NSObject (Mac App with Objective-C)

I'm making a game that needs to play music. To make my code more manageable, I wanted to make an NSObject that takes care of the sounds (like fading, playing sounds in a playlist, etc). I have this code:

NSSound *music = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:self.filename ofType:self.fileExtention] byReference:NO];
[music play];

This code works when I place it in the AppDelegate.m file but is does not work when I place it in the New NSObject Class.

Code in NSObject Class (named Music):

- (void)playMusic:(NSString *)fileName ofType:(NSString *)type
{
    NSSound *music = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:self.filename ofType:self.fileExtention] byReference:NO];
    [music play];

    NSLog(@"Works!");
}

I call the method with this code in the AppDelegate.m:

[[[Music alloc] init] playMusic:self.fileName ofType:self.extension];

When this is executed it does log "Works!" which means the code is executed.

So the exact same code works in the AppDelegate but not in a NSObject Class. Does anyone know if playing an NSSound in a NSObject Class is even possible (if not, why?), and if so how to edit the code so that it works? It would make my code look a lot less messy ;)

Upvotes: 6

Views: 275

Answers (1)

Ashish
Ashish

Reputation: 3137

Try called methods on main thread,

dispatch_async(dispatch_get_main_queue(), ^{
  // do work here
});

Upvotes: 1

Related Questions