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

标签 ios swift swift3 sprite-kit

我在尝试向游戏添加声音时遇到了问题。我在下面将其添加到 View Controller 中,当我构建并运行时,我会收到错误。当我运行下面的代码时:

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'

我收到以下错误:

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

有人可以帮忙吗?

最佳答案

当您使用Bundle.main.path(forResource:,ofType:)时,第一部分应该是资源的名称,第二部分应该是其类型。这意味着您的代码应该是:

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

关于ios - 如何在 SpriteKit 中向游戏添加音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44102098/

相关文章:

ios - 从 Firebase 数据库 Swift 3 中删除子数据

ios - 使用 Swift 在 didReceiveRemoteNotification 中呈现特定的 View Controller

ios - 根据各种屏幕尺寸自动布局 Collection View

iphone - UITableViewCell accessoryType 已设置,但 accessoryView 为 nil。如何设置 accessoryView backgroundColor?

swift - QUIZ 应用程序... UIAlertController 没有出现并且没有重新启动回到最初的问题

ios - 无法在 Swift 2.1 中访问扩展内的属性

ios - 如何在 Objective-C 中使用 NSRange 获取上限和下限?

ios - 如何向 UITextField 添加长按功能

ios - 如何在准备要在 swift iOS 中显示的数据时制作加载页面

ios - Sprite 套件触摸 userInteractionEnabled = true