1
我已经完成了应用程序的所有代码,除此之外:我想在播放按钮时播放随机声音文件。播放按下按钮时的随机声音Swift 2.0
我发现下面的代码,它编译,但按下按钮时,它什么也不做。有人可以看看它,看看有什么不对吗?在模拟器中播放应用程序时出现错误。
您可以找到下面的代码:
import AVFoundation
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var mainButton1: UIButton!
// PUT SOUNDS AS STRINGS IN ARRAY
var arrayOfSounds = ["sound1", "sound2", "sound3", "sound4"]
// Different Block of code below.
var audioPlayer: AVAudioPlayer = AVAudioPlayer()
func setupAudioPlayerWithFile(file: NSString, type: NSString) -> AVAudioPlayer? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
var audioPlayer : AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
return audioPlayer
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func buttonPressed(sender: AnyObject){
let range: UInt32 = UInt32(arrayOfSounds.count)
let number = Int(arc4random_uniform(range))
let sound = self.setupAudioPlayerWithFile(arrayOfSounds[number], type: "wav")
sound!.play()
}
}
你的答案应该解释一下什么是错的,什么样的变化,你做。不要只是在没有解释的情况下发布代码。 – rmaddy
你是对的,我会解释代码。 – UlyssesR
谢谢!我会尝试使用这些代码,并会通知您。 – Henry