当角色从地面反弹时声音播放两次?

时间:2016-12-15 14:23:19

标签: swift avfoundation avaudioplayer

所以我设置了这个功能,当我的角色撞到地面时发出声音。

 func playSound() {

    let url = Bundle.main.url(forResource: "Sound", withExtension: "caf")!

    do {
        Sound = try AVAudioPlayer(contentsOf: url)
        guard let Sound = Sound else { return }

        Sound.prepareToPlay()
        Sound.play()
    } catch let error {
        print(error.localizedDescription)
    }
}

除了1个问题之外它工作得很好 - 我的英雄正在倒地并从地面反弹,造成两次碰撞/播放声音两次。

我对如何解决此问题有任何想法?

还可以在Swift中调整声音的音量,还是需要在外部完成?非常感谢任何帮助:)

func playSound()在下面调用

    if firstBody.categoryBitMask == physicsCategory.bird && secondBody.categoryBitMask == physicsCategory.ground || firstBody.categoryBitMask == physicsCategory.ground && secondBody.categoryBitMask == physicsCategory.bird{


        playSound()


        enumerateChildNodes(withName: "wallPair", using: ({
            (node, error) in

            node.speed = 0
            self.removeAllActions()
        }))

        enumerateChildNodes(withName: "birdFly", using: ({
            (node, error) in

            node.speed = 0
            self.removeAllActions()


        }))


        if died == false{
            died = true
            createButton()
            loseALife()


        }

1 个答案:

答案 0 :(得分:1)

我必须看到你的代码(调用playSound()的函数),但你可以将playSound()包装在if语句中,只有当fall.y的fall.y大于a时才会成功一定数量。

对于音量,您可以将AVAudioPlayer的音量属性(Float)设置为0.0到1.0之间的数字。你可以将它传递给你的playSound()函数:

func playSound(with volumeForFall: CGFloat) {
    let url = Bundle.main.url(forResource: "Sound", withExtension: "caf")!

    do {
        Sound = try AVAudioPlayer(contentsOf: url)
        guard let Sound = Sound else { return }

        Sound.volume = volumeForFall

        Sound.prepareToPlay()
        Sound.play()
    } catch let error {
        print(error.localizedDescription)
    }
}

然后,拨打你可以访问translation.y的地方(在秋天经过的Y距离)并相应地设置音量。