问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/1103170/how-to-play-a-mp3-file-from-within-the-resources-folder-of-my-application