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