6

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

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
Developer
  • 406
  • 1
  • 4
  • 18
  • 2
    Are you sure that you retain your `Music` instance, i.e. that it has not been released at the time when music playing should start? – Reinhard Männer Nov 02 '17 at 16:45
  • @ReinhardMänner I don't know actually. I don't really know much about retaining and releasing. How can I make sure it hasn't been released? – Developer Nov 02 '17 at 18:18
  • I don’t think it matters where you put the code; however it probably matters in which context you run it. When in appdelegate, probably your code runs in main thread context. So maybe you should put this code in a block and run it in main thread to see if it makes any difference. – manishg Nov 03 '17 at 12:13
  • Are you actually sure that file exists? It should work even if you're not using ARC, so I don't really think that's the problem... – animaonline Nov 09 '17 at 09:54

1 Answers1

1

Try called methods on main thread,

dispatch_async(dispatch_get_main_queue(), ^{
  // do work here
});
Ashish
  • 2,977
  • 1
  • 14
  • 32