如何在类中定义和播放音效
这是一个精灵类,它可以在屏幕上左右移动。当它碰到边界时,会发出“弹跳”的声音,然后朝相反的方向移动。整体运行得很好,唯一的问题是,当它碰到边缘时没有发出弹跳声。
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 个回答
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)
这些名字有点糟糕,因为除了大小写不同外都是一样的,但不管怎样,这种方法可能会更清晰。你可以在声音传给精灵之前就设置好音量,以及你觉得需要的其他调整。