views:

228

answers:

2

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.

+3  A: 

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.

Perspx
Almost the same I found : NSSound *player = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForSoundResource:@"Winner.mp3"] byReference:NO];Thanks ;)
Fantattitude
A: 

Just to clarify why your initial solution didn't work:

Relative paths are relative to the current working directory. For a GUI app launched from the Finder, the initial working directory is / — that is, the root of the file-system. If it were the Resources folder of your bundle, your solution would have worked.

As Perspx noted in his answer, the correct solution is to ask your bundle to convert the relative path to a full path.

Peter Hosey