ボタンが押されたときにオーディオを追加しようとしていますが、使用するコードには実行するまでエラーがありません。次に、「致命的なエラー: オプション値のアンラップ中に予期せず nil が見つかりました」というメッセージが表示されます。 :
let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
これは参照用の私のコード全体です:
import UIKit
import AVFoundation
class ViewController: UIViewController {
let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]
var audioPlayers = [AVAudioPlayer]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for sound in soundFilenames {
do {
let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
let audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayers.append(audioPlayer)
}
catch {
audioPlayers.append(AVAudioPlayer())
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonTapped(_ sender: UIButton) {
let audioPlayer = audioPlayers[sender.tag]
audioPlayer.play()
}
}
エラーは自己記述的です: url(forResource: withExtension:)
nil を返し、それを強制的にラップ解除すると!
、クラッシュが発生します。
このクラッシュを修正するには、次のことを再確認してください。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加