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 ;)
Try called methods on main thread,
dispatch_async(dispatch_get_main_queue(), ^{
// do work here
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With