如何在Xcode中将声音文件添加到包中?

S.B*_*tia 3 xcode bundle file ios

我正在尝试制作一个有声音的应用程序。在向Xcode中的应用程序添加声音之前,我曾问过一个问题,但是每次我运行该应用程序时,控制台都会引发此错误,MagicSound.wav does not exist in main bundle在编写代码时,我基本上告诉程序使应用程序崩溃并编写,MagicSound.wav does not exist in main bundle如果它是真的, 。我的问题是如何在Xcode中将文件(特别是声音文件)添加到包中。我一直认为将文件放入资产与将其放入捆绑包是一样的。

这是我的代码,

`导入UIKit导入AVFoundation

类ViewController:UIViewController {

var magicSound: AVAudioPlayer = AVAudioPlayer()


@IBOutlet var Answer: UILabel!

var AnswerArray = ["Yes", "No", "Maybe", "Try Again", "Not Now", "No Doubt", "Yes Indeed", "Of course", "Definetley Not"]
var chosenAnswer = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    if let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: "wav") {
        _ = try? AVAudioPlayer(contentsOf: URL (fileURLWithPath: magicFile))
    }
    else {
        print( "MagicSound.wav does not exist in main bundle" )
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {

    if event?.subtype == motion {
        printAnswer()
        randomAnswer()
        animation()
        showingAnswerAnimation()
        magicSound.play()
    }

}`
Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助,那就太好了!

谢谢。

Jos*_*nce 9

这个答案是Google搜索“如何在Xcode中将声音文件添加到您的包中?”的顶部,因此,为了帮助像我这样的菜鸟,这里逐步介绍了如何在Xcode中将声音添加到您的包中。(简短的回答,只需将其拖到侧边栏中,然后选中“如果需要,复制项目”即可)

  1. 将声音放在文件夹中(您不必但要使声音井井有条)

  2. 将声音文件夹拖到Xcode的侧栏中。 在此处输入图片说明

  3. 当您将文件夹拖入时,它将为您提供一些选择。确保选中“如果需要复制项目”。它应该是默认值。 在此处输入图片说明

  4. 大功告成!通过获取基于文件名的路径和URL来访问声音。

像这样:

func playSaveSound(){
    let path = Bundle.main.path(forResource: "upward.wav", ofType: nil)!
    let url = URL(fileURLWithPath: path)

    do {
        //create your audioPlayer in your parent class as a property
        audioPlayer = try AVAudioPlayer(contentsOf: url)
        audioPlayer.play()
    } catch {
        print("couldn't load the file")
    }
}
Run Code Online (Sandbox Code Playgroud)

本文对如何播放声音进行了很好的概述。

  • 对我来说,这里的关键是在步骤 3 中选择“创建组”而不是“创建文件夹引用”,非常感谢! (4认同)

use*_*779 5

这里有一个额外的步骤,XCode 是隐式执行的,并且可以将您的东西配置为无法完成的方式。您需要确保 wav 文件位于目标的 Build Phases -> Copy Bundle Resources 设置下的项目列表中。

如果您的应用程序只有一个主要目标并且没有什么特别的,那么当您将文件添加到 XCode 中的文件夹时,这应该会自动完成。但是我有一个奇怪的设置,它不是,我不得不挖掘才能找到它。


Par*_*Dev 2

按着这些次序:

  1. 将声音文件拖到 Xcode 侧边栏,将其添加到项目中
  2. 将出现一个对话框 - 检查Copy items needed并添加文件。
  3. 要测试文件是否已正确添加,请在 Xcode 中右键单击任何添加的文件,然后单击show in Finder。如果该文件存在,那么在运行时它不会抛出错误。