作成したゲームに音楽を追加しようとしています。しかし、私はエラーが発生しています:
「スレッド1:致命的なエラー:オプションの値をアンラップしているときに予期せずnilが見つかりました。
Stack Overflowで別の投稿を見つけました(「致命的なエラー:オプションの値をアンラップしているときに予期せずnilが見つかりました」とはどういう意味ですか?)が、これが私のコードにどのように適用されるかわかりません。
これは私のコードです:
import UIKit
import SpriteKit
import GameplayKit
import AVFoundation
class GameViewController: UIViewController {
var player:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
do {
let audioPath = Bundle.main.path(forResource: "HomeSoundtrack", ofType: "m4a")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch {
}
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
}
catch {
}
player.play()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = false
view.showsNodeCount = false
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
}
オプションの値は、値を取得する場合に含めることができる値でありnil
、ラップする必要があります
ただし、強制ラッピングではなく、安全なラッピングを使用してください !
この行を確認してください
let audioPath = Bundle.main.path(forResource: "HomeSoundtrack", ofType: "m4a")
audioPathはAnであるOptional
ため、間違ったnil
書き込みHomeSoundtrack
またはファイルが見つからないと想定して値が含まれている可能性があり、audioPathはnilになります
次に、それを強制的にラップ!
します。この行にある場合audioPath
はnil
クラッシュします
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
安全に行うことができます
let audioPathURL = Bundle.main.url(forResource: "HomeSoundtrack", withExtension: "m4a")
{
do {
player = try AVAudioPlayer(contentsOf: audioPathURL)
} catch {
print("Couldn't load HomeSoundtrack file")
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加