如何从我的应用程序的 Resources 文件夹中播放 mp3 文件?
我正在制作一个可以在事件中播放声音的应用程序,但我不知道如何从应用程序的资源文件夹中访问文件。
这就是我正在做的事情:
NSSound *player = [[NSSound alloc] initWithContentsOfFile:@"Sound.mp3"] byReference:NO];
[player play];
但它根本不起作用。 如果我放置完整的路径,它会起作用,但我需要另一种方法,因为有人可能会将我的应用程序放在应用程序文件夹之外的其他位置。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
NSBundle
类,使用pathForResource:ofType:
方法引用文件:这将返回所传递资源的完整路径名到方法。
You need to use the
NSBundle
class with thepathForResource:ofType:
method to reference the file:This returns the full pathname for the resource passed to the method.
只是为了澄清为什么您的初始解决方案不起作用:
相对路径是相对于当前工作目录的。 对于从 Finder 启动的 GUI 应用程序,初始工作目录是 / — 即文件系统的根目录。 如果它是您的捆绑包的 Resources 文件夹,您的解决方案就会起作用。
正如 Perspx 在他的回答中指出的那样,正确的解决方案是要求您的包将相对路径转换为完整路径。
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.