2016-12-15 49 views
2

所以我已經設置了這個功能,當我的角色擊中地面時發出聲音。當角色從地面反彈時聲音播放兩次?

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

我得看看你的代碼(其中playSound()被調用的FUNC),但你可以換playSound ()在一個if語句中,只有當fall.y的翻譯大於某個數時纔會成功。

至於音量,您可以將AVAudioPlayer的音量屬性(Float)設置爲範圍從0.0到1.0的數字。你可以在它傳給你的playSound()FUNC:

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距離在秋季遍歷),並相應地設置音量。

+0

謝謝你送我正確的方向!由於swift的更新版本,我認爲這個數量已經發生了變化。 在playSound()函數調用後立即添加了flap?.volume = 0.1 我已將我的代碼的其餘部分添加到頂部,我的玩家死亡並落到地面上。謝謝你的幫助! – niX