JR_22 JR_22 -4 years ago 78
Swift Question

How to add music to game in spitekit

can some one help i ran into an issue when trying to add sound to my game i added this below to the viewcontrolller and when i build and run i would get an error when i ran the code below

var interstitialAd : GADInterstitial!

var player: AVAudioPlayer!



override func viewDidLoad() {
super.viewDidLoad()

let path = Bundle.main.path(forResource: "gameMusic.mp3", ofType:"mp3")!
let url = URL(fileURLWithPath: path)

do {
let sound = try AVAudioPlayer(contentsOf: url)
player = sound
sound.play()
} catch {
print("file not found")
}




if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'


THIS BELOW IS THE ERROR I GET

fatal error: unexpectedly found nil while unwrapping an Optional value
2017-05-21 17:35:01.262683 gameTest2[1660:363851] fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

Answer Source

When you use Bundle.main.path(forResource:,ofType:) the first part should be the name of the resource, the second part should be its type. That means your code should be:

let path = Bundle.main.path(forResource: "gameMusic", ofType:"mp3")!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download