我有背景音乐,当使用以下代码在GameViewController.swift中启动应用程序时启动:
class GameViewController: UIViewController {
// VARIABLES
var backgroundMusicPlayer : AVAudioPlayer!
// AUDIO PLAYER
func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
var error : NSError? = nil
do {
backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: url!)
} catch let error1 as NSError {
error = error1
backgroundMusicPlayer = nil
}
if backgroundMusicPlayer == nil {
print("Could not create audio player: \(error!)")
return
}
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}
func stopBackgroundMusic() {
backgroundMusicPlayer.stop()
}
override func viewDidLoad() {
super.viewDidLoad()
playBackgroundMusic("MainTheme.mp3")
<< Various irrelevant code >>
}
因为这是在viewController中运行的,所以它会通过改变菜单上的场景(即打开“商店”场景)而持续存在并创建无缝轨道。当我点击菜单场景中的“播放”按钮时,我希望音乐停止,然后转换到游戏。我在GameViewController中有stopBackgroundMusic()方法,但我不知道如何在菜单场景中调用它。 在菜单场景中我尝试了这个:
// TOUCH
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first as UITouch?
let touchLocation = touch!.locationInNode(self)
let touchedNode = self.nodeAtPoint(touchLocation)
if touchedNode.name == "startGame" {
GameViewController.stopBackgroundMusic()
let transitionType = SKTransition.fadeWithDuration(2)
let viewSize = self.view?.bounds.size
let scene = GameScene(size: viewSize!)
self.view?.presentScene(scene, transition: transitionType)
}
}
但是我得到一个错误,说我在调用stopBackgroundMusic()时缺少参数#1,它不需要任何参数。我称这种方法错了吗?谢谢!
答案 0 :(得分:2)
您通过使用GameViewController引用您的类,但您的函数位于对象实例级别。
如果在类级别声明变量和函数,touchesBegan函数中的代码应该可以正常工作。
static var backgroundMusicPlayer : AVAudioPlayer!
class func playBackgroundMusic(filename: String) ...
class func stopBackgroundMusic()
override func viewDidLoad() {
super.viewDidLoad()
GameViewController.playBackgroundMusic("MainTheme.mp3")
<< Various irrelevant code >>
}