Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ;)

like image 265
Developer Avatar asked Oct 31 '17 12:10

Developer


1 Answers

Try called methods on main thread,

dispatch_async(dispatch_get_main_queue(), ^{
  // do work here
});
like image 168
Ashish Avatar answered Sep 28 '22 06:09

Ashish