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

核能气质少年 提交于 2019-12-24 08:47:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!