Search code examples
objective-ccocoamacosnssound

How to play a mp3 file from within the Resources folder of my application?


I am making an app that will play sound on events but I can't figure out how to access files from the ressources folder of the Application.

Here is what I'm doing :

NSSound *player = [[NSSound alloc] initWithContentsOfFile:@"Sound.mp3"] byReference:NO];
[player play];

But it's not working at all. If I put a full length path it will work but I need another way because someone might put my app in an other place than the Application folder.


Solution

  • You need to use the NSBundle class with the pathForResource:ofType: method to reference the file:

    NSSound *player = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"mp3"] byReference:NO];
    [player play];
    

    This returns the full pathname for the resource passed to the method.