问题描述
我正在尝试制作一个游戏,在主菜单中,有一个标签用于开始音乐,另一个标签用于停止音乐。
let backgroundMusic = SKAction.playSoundFileNamed("background.mp3",waitForCompletion: false)
override func touchesEnded(_ touches: Set<UITouch>,with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let touchedNode = atPoint(location)
if touchedNode.name == self.BEGIN_MUSIC {
// start music
self.run(backgroundMusic)
}
if touchedNode.name == self.STOP_MUSIC {
// stop music
SKAction.stop()
}
}
}
音乐开始很好,适用于我想要的所有场景。但是当我按下停止音乐时,音乐继续播放。如何停止音乐。
我试过 SKAction.pause(),我试过使用 withKey: "music" 然后 self.removeAction(forKey: "music")。
我也尝试制作 backgroundMusic: SKAudioNode 并且这有效,但是一旦我停止音乐,我就无法重新打开它,它也不适用于仅主菜单的任何其他场景。
如何停止声音?
解决方法
不久前我遇到了同样的问题:这就是我让它工作的方式。这是特定于背景音乐的。
var backgroundMusic: AVAudioPlayer!
func playMusic() {
if let musicURL = Bundle.main.url(forResource: "musicSource",withExtension: "wav") {
if let audioPlayer = try? AVAudioPlayer(contentsOf: musicURL) {
backgroundMusic = audioPlayer
backgroundMusic.numberOfLoops = -1
backgroundMusic.play()
backgroundMusic.volume = 0.2
}
}
}
override func touchesEnded(_ touches: Set<UITouch>,with event: UIEvent?) {
super.touchesBegan(touches,with: event)
if let touch = touches.first {
let pos = touch.location(in: self)
let node = self.atPoint(pos)
let musicOff = UserDefaults.standard.bool(forKey: "musicOff")
if node == musicButton && musicOff == false {
backgroundMusic.stop()
UserDefaults.standard.set(true,forKey: "musicOff")
}
if node == musicButton && musicOff == true {
backgroundMusic.play()
backgroundMusic.volume = 0.3
UserDefaults.standard.set(false,forKey: "musicOff")
}
}
}