我正在试图快速制作一个声音板应用程序,四个按钮中的三个会使应用程序崩溃而另一个没有做任何事情。 我究竟做错了什么? 我是编程的新手,我试图按照教程进行操作,但它不起作用。
import AVFoundation
import UIKit
class FirstViewController: UIViewController {
let soundFilesname = ["Tacos", "What's that supposed to mean", "Cube fist man", "giraffe"]
var audioPlayers = [AVAudioPlayer]()
override func viewDidLoad() {
super.viewDidLoad()
//set up audio player
for sound in soundFilesname {
do{
//try and do somthing
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)
audioPlayers.append(audioPlayer)
}
catch{
//catch error that is thrown
audioPlayers.append(AVAudioPlayer())
}
}
}
@IBAction func buttonTapped(sender: AnyObject)
{
//get the audioplayer thats corresponds to the button pressed
let audioPlayer = audioPlayers [sender.tag]
audioPlayer.play()
}
}
更新
在我的iPhone 5 IOS 9.0.2上通过Xcode运行应用程序:
IOS模拟器:
答案 0 :(得分:0)
请提供点击按钮时获得的崩溃信息。
另外,在buttonTapped中打印以检查正确的标记号,可能是您正在从数组中访问越界元素,但不确定,除非您提供崩溃信息。
@IBAction func buttonTapped(sender: AnyObject)
{
// to check correct tag no
print("Button tag is \(sender.tag)")
//get the audioplayer thats corresponds to the button pressed
let audioPlayer = audioPlayers [sender.tag]
audioPlayer.play()
}