简体   繁体   English

如何在我的iOS / Xcode项目中添加MP3?

[英]How do I add an MP3 to my iOS/Xcode project?

I am trying to program an app that includes several songs. 我正在尝试编写包含多首歌曲的应用程序。 Looking through various tutorials they just say to "add your file to the project" or some such so I have tried adding my MP3 to various places (including xcassets) but it is never copied to the output of my project or played. 通过各种教程,他们只是说“将您的文件添加到项目”或其他一些,所以我尝试将我的MP3添加到各个地方(包括xcassets),但它永远不会复制到我的项目的输出或播放。

In other words, this always return nil: 换句话说,这总是返回nil:

let path = NSBundle.mainBundle().pathForResource(audioFile, ofType: "mp3")

This seems dead simple stuff and it is driving me crazy that it won't simply play the file. 这似乎是死的简单的东西,它让我发疯,它不会简单地播放文件。 I have tried it in the root directory, a directory that I create named "resources" (since several sources say to "add it to resources"), and even in the xcassets. 我在根目录中尝试过它,我创建了一个名为“resources”的目录(因为有几个消息来源称“将它添加到资源”),甚至在xcassets中也是如此。 However, it always comes back nil. 然而,它总是回来零。

Note that I am in Xcode 7 (the beta) developing for the latest iOS and using Swift 2. The file is about 53MB in size. 请注意,我在Xcode 7(测试版)中为最新的iOS开发并使用Swift 2.该文件大小约为53MB。

Any help is very much appreciated! 很感谢任何形式的帮助!

It really is that simple. 它真的很简单。 The only thing that you might have missed is that audioFile should really only contain the name, not the file extension. 你唯一可能错过的是audioFile应该只包含名称,而不是文件扩展名。 But beyond that it is as easy as dragging the file into your project and you can play it. 但除此之外,它就像将文件拖入项目一样简单,您可以播放它。

In the following gif I have code that plays an audio file and does some manipulation to answer this question . 在下面的gif我有代码播放音频文件并做一些操作来回答这个问题 But basically it just loads an audio file the same way you try it. 但基本上它只是加载一个音频文件,就像你尝试它一样。

  • I run the program at first to show that is in fact crashing without the file 我首先运行程序,以显示实际上没有文件崩溃
  • Then I dragged the file into Xcode 然后我将文件拖入Xcode
  • Running the app again works as expected 再次运行应用程序按预期方式工作

截屏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM