如何将 MP3 添加到我的 iOS/Xcode 项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33987906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:16:00  来源:igfitidea点击:

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

iosxcodensbundle

提问by Mark Brittingham

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 simplestuff 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. However, it always comes back nil.

这看起来很简单,而且它不会简单地播放文件让我发疯。我已经在根目录中尝试过它,我创建了一个名为“resources”的目录(因为有几个消息来源说要“将它添加到资源中”),甚至在 xcassets 中。但是,它总是返回零。

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!

很感谢任何形式的帮助!

回答by luk2302

It really is that simple. The only thing that you might have missed is that audioFileshould really only contain the name, not the file extension. But beyond that it is as easy as dragging the file into your project and you can play it.

真的就是这么简单。您可能错过的唯一一件事是它audioFile应该只包含名称,而不是文件扩展名。但除此之外,只需将文件拖入您的项目即可轻松播放。

In the following gif I have code that plays an audio file and does some manipulation to answer this question. But basically it just loads an audio file the same way you try it.

在下面的 gif 中,我的代码可以播放音频文件并进行一些操作来回答这个问题。但基本上它只是以与您尝试相同的方式加载音频文件。

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

Screencast

截屏