[英]How to add sound files to your bundle in Xcode?
我正在尝试制作一个有声音的应用程序。 我在如何在 Xcode 中向应用程序添加声音之前问过一个问题,但是每次运行应用程序时,控制台都会抛出此错误,编写代码时MagicSound.wav does not exist in main bundle
我基本上告诉程序崩溃application 和 write MagicSound.wav does not exist in main bundle
如果它成为真的MagicSound.wav does not exist in main bundle
。 我的问题是如何将文件(特别是声音文件)添加到 Xcode 中的包中。 我一直认为将文件放入您的资产中与将其放入您的包中是一回事。
这是我的代码,
import UIKit
import AVFoundation
class 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()
}
}
如果有人可以提供帮助,那就太好了!
谢谢。
这个答案是 Google 搜索“如何在 Xcode 中将声音文件添加到您的包中?”的顶部,因此为了帮助像我这样的新手,这里将逐步介绍如何在 Xcode 中将声音添加到您的包中。 (简短的回答,只需将它们拖到侧边栏中并选中“如果需要复制项目”)
将声音放在一个文件夹中(你不必,但要保持它们的组织性)
你完成了! 通过根据文件名获取路径和 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")
}
}
这篇文章对如何播放声音有一个很好的概述。
这里有一个额外的步骤,XCode 是隐式执行的,并且可以将您的东西配置为无法完成的方式。 您需要确保 wav 文件位于目标的 Build Phases -> Copy Bundle Resources 设置下的项目列表中。
如果您的应用程序只有一个主要目标并且没什么特别的,那么当您将文件添加到 XCode 中的文件夹时,这应该会自动完成。 但是我有一个奇怪的设置,它不是,我不得不挖掘才能找到它。
按着这些次序:
Copy items needed
并添加文件。show in Finder
。 如果文件存在,那么在运行时它不会抛出错误。除了这里的其他答案之外,要添加的另一件事是,当您导入时,您需要确保将其复制到您的应用程序中,位于“添加到目标”中。 这完成了声音文件位于“目标的构建阶段-> 复制捆绑资源设置下的项目列表”中。
您需要正确处理所有这些事情,否则它就不会出现在捆绑包中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.