隨機音頻文件我不斷收到以下錯誤,當我使用「搖晃手勢」在iPhone模擬器:播放使用雨燕
Fatal error: unexpectedly found nil while unwrapping an Optional value
這裏是我的相關代碼:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var soundFiles = ["kidLaughing", "pewpew", "pingas", "runningfeet"]
var player: AVAudioPlayer = AVAudioPlayer()
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
if event.subtype == .MotionShake {
var randomSoundFile = Int(arc4random_uniform(UInt32(soundFiles.count)))
var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!)
var error: NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: fileLocation), error: &error)
player.play()
}
}
}
我有一個名爲sounds
的文件夾,其中有4個mp3
文件。該錯誤是發生在這行代碼:
var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!)
我已經試過所有我能想到的來得到這個工作,但沒有我曾嘗試工作過。任何幫助表示讚賞!
完美!謝謝! – Jeff 2016-11-13 21:35:41
你永遠歡迎 – Rex 2017-02-07 08:20:39