【问题标题】:Sounds do not play from new class新班级不播放声音
【发布时间】:2014-12-08 19:17:37
【问题描述】:

我是一位经验丰富的程序员,但对 iOS 和 Swift 不熟悉。我已经建立了一个带有声音的俄罗斯方块游戏教程。我正在尝试重构代码并将声音例程移至指定的类。正在调用新类中的函数,但不再播放声音。

原始代码(作品):

GameScene.swift

import SpriteKit
...
class GameScene: SKScene {
  ...
  runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed("theme.mp3", waitForCompletion: true)))
}

新代码(没有声音播放):

声音.swift

import SpriteKit

class Sounds: SKNode {

    required init(coder aDecoder: NSCoder) { fatalError("NSCoder not supported") }
    override init() { super.init() }

    func playSoundtrack() {
        println( "Sounds: playSoundtrack: ")
        runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed("theme.mp3", waitForCompletion: true)))
    }
}

将上面的GameScene代码修改如下:

class GameScene: SKScene {
  var soundEngine: Sounds   = Sounds()
  ...
  soundEngine.playSoundtrack()
}

我确认 println 已执行,但没有声音播放。有什么想法吗?

【问题讨论】:

  • 您在哪个对象/节点上调用runAction?您在控制台中遇到任何错误吗?
  • 这是问题所在,不是在节点上运行它。控制台没有错误。将类添加到场景中并且它可以工作。谢谢!

标签: ios swift sprite-kit


【解决方案1】:

来自 Apple 的文档

SKAction 对象是由节点中执行的操作 场景

您需要将soundEngine 添加到场景中

self.addChild(soundEngine)
soundEngine.playSoundtrack()

或将场景传递给playSoundtrack 方法并在场景上运行动作

soundEngine.playSoundtrack(self)

func playSoundtrack(SKScene *scene) {
    scene.runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed("theme.mp3", waitForCompletion: true)))
}

当然,如果您选择后者,最好直接从 SKScene 子类运行操作。

【讨论】:

  • 就是这样——addChild(soundEngine)。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 2011-02-25
  • 2020-02-15
  • 2015-12-22
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多