【发布时间】:2015-09-13 17:12:03
【问题描述】:
所以我正在尝试创建一个变量,我可以使用它从我创建的 NSURL 数组中选择随机声音。这是数组,也就是导致错误的那一行:
var levelOneSounds =
[
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Barn", ofType: "mp3")!),
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Chicken", ofType: "mp3")!),
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Birds", ofType: "mp3")!),
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Camera", ofType: "mp3")!), NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Cat", ofType: "mp3")!),
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Crickets", ofType: "mp3")!),
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Glass", ofType: "mp3")!),
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Siren", ofType: "mp3")!), NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Slap", ofType: "mp3")!),
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Snoring", ofType: "mp3")!),
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Toilet Flushing", ofType: "mp3")!),
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Wolves Howling", ofType: "mp3")!)
]
显然,所有这些都是我存储在 Supporting Files 文件夹中的 mp3 文件。我还在这里创建了音频播放器:
var levelOneAudioPlayer = AVAudioPlayer()
这是我的 viewDidLoad() 方法,我在其中创建随机声音变量并播放该声音:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var randomSound = levelOneSounds[Int(arc4random_uniform(UInt32(levelOneSounds.count)))]
levelOneAudioPlayer = AVAudioPlayer(contentsOfURL: randomSound, error: nil)
levelOneAudioPlayer.play()
}
但是,每当我运行它并进入此视图控制器时,我都会在数组中收到以下错误:
线程 1:EXC_BAD_INSTRUCTION(代码 = EXC_1386_INVOP,子代码 = 0 x 0)
我能做些什么来解决这个问题,以便播放随机声音?我是编程新手,所以如果我犯了明显的错误,我深表歉意。谢谢!
这里是资源文件夹照片的链接: http://i.stack.imgur.com/bj3yG.png
【问题讨论】:
-
哪一行导致错误?
-
数组初始化导致错误?你检查过 NSBundle.mainBundle().pathForResource aint nil 吗?
-
聊天第一行代码:var levelOneSounds @MustangXY
-
我看了一个关于如何将声音添加到项目中的视频教程,我基本上复制了视频中所做的事情,除了我将声音放入一个数组中,而不是将一个声音放入单个变量中,所以我不太确定。就像我说的,我是编程新手@Neo
-
发生崩溃是因为其中一个(可选)URL 在为
nil时被解包。检查文件名的拼写,我猜有错字或文件丢失
标签: ios arrays swift audio nsurl