简体   繁体   English

如何在SpriteKit中向游戏添加音乐

[英]How to add music to a game in SpriteKit

I ran into an issue when trying to add sound to my game. 尝试在游戏中添加声音时遇到问题。 I added this below to the view controller 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'

I got the following error: 我收到以下错误:

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 致命错误:展开一个可选值时意外发现nil 2017-05-21 17:35:01.262683 gameTest2 [1660:363851]致命错误:展开一个可选值时意外发现nil

Can anyone help? 有人可以帮忙吗?

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. 当您使用Bundle.main.path(forResource:,ofType:) ,第一部分应该是资源的名称,第二部分应该是资源的类型。 That means your code should be: 这意味着您的代码应为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM