如何在课堂上定义和播放声音效果

时间:2014-04-18 17:15:18

标签: python pygame

这是一个精灵的类,它在屏幕上左右移动,当它到达边界时,它发出“boing”声并向相反的方向发射,除了没有声音之外,一切都很好当它到达边缘时

class MySprite(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load("vegetables.gif")
        self.image = self.image.convert()

        self.rect = self.image.get_rect()
        self.rect.left = 0
        self.rect.top = 167
        self.__direction = 10


    def update(self):
        self.rect.left += self.__direction
        sound = pygame.mixer.Sound("Bounce.mp3")
        sound.set_volume(0.5)
        if (self.rect.left < 0) or (self.rect.right > screen.get_width()):          
            sound.play()
            self.__direction = -self.__direction

1 个答案:

答案 0 :(得分:2)

如果您希望课程播放自己的声音,只需像__init__上的任何属性一样加载它。

class MySprite(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load("vegetables.gif")
        self.image = self.image.convert()
        self.sound = pygame.mixer.Sound("Bounce.mp3")   #like this
        self.rect = self.image.get_rect()
        self.rect.left = 0
        self.rect.top = 167
        self.__direction = 10

然后,只要这样做,只需拨打self.sound.play()

  def update(self):
        self.rect.left += self.__direction
        if (self.rect.left < 0) or (self.rect.right > screen.get_width()):          
            self.sound.play()                    #as seen here
            self.__direction = -self.__direction

无论它有什么价值 - 如果你要以这种方式去做(让精灵发挥自己的声音等),我建议事先加载它们然后将它们作为参数传递(可能是默认参数以避免错误),如果需要,该类的每个实例都可以调用一个独特的声音。

因此,在您的代码之前这些类中,可以执行以下操作:

JumpSound = pygame.Mixer.Sound("jump.wav")
BonkSound = pygame.Mixer.Sound("bonk.wav")
#etc etc etc...

...然后,将声音作为参数传递:

class MySprite(pygame.sprite.Sprite):
    def __init__(self, jumpsound, bonksound):
        #...your other code precedes...
        self.jumpsound = jumpsound
        self.bonksound = bonksound
        #...your other code continues...

myHero = MySprite(JumpSound, BonkSound)

名字有点糟糕b / c他们是相同的禁止CamelCasing,但忘记了,这可能是一个更清洁的方法。您可以在声音传递到精灵之前设置音量,以及在精灵获得它们之前您认为必要的任何其他变化。

相关问题