我的声音效果循环的代码是什么

时间:2017-05-10 19:02:17

标签: ios swift sprite-kit

我正在制作一款充满乐趣的游戏,我想在每次结束时制作声音效果循环,这些是我的代码到目前为止。

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let touchLocation = touch.location(in: self)
        if atPoint(touchLocation).name == "startGame"{
            let gameScene = SKScene(fileNamed: "GameScene")!
            gameScene.scaleMode = .aspectFill
            view?.presentScene(gameScene, transition: SKTransition.doorsOpenHorizontal(withDuration: TimeInterval(2)))
            self.run(SKAction.playSoundFileNamed("mainmenu.wav", waitForCompletion: false))

3 个答案:

答案 0 :(得分:1)

使用SKActions无法在场景中播放背景音乐。改为使用AVAudioPlayer:

if let filePath = Bundle.main.path(forResource: "mainmenu", ofType: "wav") {
    let url = URL(fileURLWithPath: filePath)
    do {
        let player = try AVAudioPlayer(contentsOf: url)
        player.numberOfLoops = -1
        player.play()
    } catch {
        // catch error if necessary
    }
}

原帖: https://stackoverflow.com/a/23268462/6846532

答案 1 :(得分:1)

在gamescene中,或者您希望音乐循环使用的任何其他场景

 let music  = SKAudioNode(fileNamed: "backgroundmusic.mp3")

  music.autoplayLooped = true
    addChild(music)

答案 2 :(得分:0)

就个人而言,我会选择AVAudioPlayerSKAudioNode因为playSoundFileNamed在许多SpriteKit版本中变成了错误,但我会告诉你如何通过行动来实现它:

import SpriteKit

class GameScene: SKScene {

    override func didMove(to view: SKView) {

        run(SKAction.repeatForever(SKAction.playSoundFileNamed("sound", waitForCompletion: true)))
    }
}
相关问题