Xcode 7.0.1 Swift 2 iOS 9を使用しています。サウンドの再生中に、次のエラーが発生します。
「致命的なエラー:オプションの値をアンラップしているときに予期せずnilが見つかりました」
これが私のコードです:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
playSound(enumerator![indexPath.item] )
}
func playSound(soundName: String)
{
let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!)
do{
let audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}
NSBundle pathForResource(name: String?, ofType ext: String?) -> String?
オプションを返し、強制的にアンラップします。パスが間違っているか、リソースがありません。
そして、画像を見ると音名には.m4a
拡張子があります。自分で拡張機能を提供する場合は、拡張機能をスキップofType
しnil
てリソースの名前から渡すか分離して、両方のパラメーターを送信できます。
安全のため、価値があるかどうかわからない場合は、常にオプションを確認する必要があります
let pathComponents = soundName.componentsSeparatedByString(".")
if let filePath = NSBundle.mainBundle().pathForResource(pathComponents[0], ofType: pathComponents[1]) {
let coinSound = NSURL(fileURLWithPath: filePath)
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加