Pygame - Sound 声音对象
音乐和声音的使用使任何电脑游戏都更具吸引力。 Pygame 库通过 pygame.mixer 模块支持此功能。 该模块包含用于加载 Sound 对象和控制播放的 Sound 类。 所有声音播放都混合在后台线程中。 为减少滞后声音,请使用较小的缓冲区大小。
要从声音文件或文件对象中获取 Sound 对象,请使用以下构造函数 −
pygame.mixer.Sound(filename or file object)
Sound 类定义了以下控制播放的方法 −
| play(loops=0, maxtime=0, fade_ms=0) | 开始在可用频道上播放声音(即,在计算机的扬声器上)。 Loops 参数用于重复播放。 |
| stop() | 这将停止在所有活动通道上播放此声音。 |
| fadeout(time) | 这将在以毫秒为单位的 time 参数淡出后停止播放声音。 |
| set_volume(value) | 这将设置此声音的播放音量,立即影响正在播放的声音以及此声音的任何未来播放。 0.0 到 1.0 范围内的音量 |
| get_length() | 以秒为单位返回此声音的长度。 |
在下面的示例中,文本按钮呈现在显示窗口的底部。 空格键会在播放声音的同时显示向上的箭头。
font = pygame.font.SysFont("Arial", 14)
text1=font.render(" SHOOT ", True, bg)
rect1 = text1.get_rect(midbottom=(200,300))
img=pygame.image.load("arrow.png")
rect2=img.get_rect(midtop=(200, 270))
在游戏事件循环中,对于检测到的空格键,arrow 箭头对象位于 SHOOT 按钮上方,并使用递减的 y 坐标重复渲染。 声音也同时播放。
sound=pygame.mixer.Sound("sound.wav")img=pygame.image.load("arrow.png")
rect2=img.get_rect(midtop=(200, 270))
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: 18. Pygame — Sound objects
print ("space")
if kup==0:
screen.blit(img, (190,y))
kup=1
if kup==1:
y=y-1
screen.blit(img, (190,y))
sound.play()
if y<=0:
kup=0
y=265
示例
以下清单演示了 Sound 对象的使用。
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
white = (255,255,255)
bg = (127,127,127)
sound=pygame.mixer.Sound("sound.wav")
font = pygame.font.SysFont("Arial", 14)
text1=font.render(" SHOOT ", True, bg)
rect1 = text1.get_rect(midbottom=(200,300))
img=pygame.image.load("arrow.png")
rect2=img.get_rect(midtop=(200, 270))
kup=0
psmode=True
screen = pygame.display.set_mode((400,300))
screen.fill(white)
y=265
while not done:
for event in pygame.event.get():
screen.blit(text1, rect1)
pygame.draw.rect(screen, (255,0,0),rect1,2)
if event.type == pygame.QUIT:
sound.stop()
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print ("space")
if kup==0:
screen.blit(img, (190,y))
kup=1
if kup==1:
y=y-1
screen.blit(img, (190,y))
sound.play()
if y<=0:
kup=0
y=265
pygame.display.update()

