Menu
CoddyTech

加载音效

本课属于 Coddy Pygame 学习旅程的“音效与游戏体验”单元。第 1 课,共 23 课。

pygame 通过 pygame.mixer.Sound 播放短音效。传入音效文件的路径,就能获得一个 Sound 对象:

jump_sound = pygame.mixer.Sound("assets/sounds/jump.ogg")

pygame.init() 会启动混音器,所以要在它之后创建 Sound。每个 Sound 只创建一次,并且要在循环之前创建。加载时会从磁盘读取文件,如果在循环内加载,每秒就会读取 60 次。

到了播放时机,调用 play():

jump_sound.play()

play() 会启动音效并立即返回。你听音效时,游戏会继续运行,而且同一个 Sound 可以在播放结束前再次播放。

assets/sounds/ 文件夹中有你可以使用的音效:jump、coin、powerup、laser、explosion、hit 等,都是 .ogg 文件。打开游戏旁边的 Assets 选项卡即可试听。

challenge icon

挑战

简单

让绿色方块跳跃时播放声音。

  1. 在循环之前,将 assets/sounds/jump.ogg 加载到 jump_sound 中。
  2. 在跳跃开始的位置,也就是 speed_y = -14 旁边,调用 jump_sound.play()。

点击“开始”,然后按空格键:你会听到跳跃的声音。接着点击“检查”。

亲手试试

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Jump")
clock = pygame.time.Clock()

player = pygame.Rect(220, 280, 40, 40)
speed_y = 0

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and player.bottom == 320:
                speed_y = -14

    speed_y += 1
    player.y += speed_y
    if player.bottom > 320:
        player.bottom = 320
        speed_y = 0

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 80, 100), (0, 320, 480, 40))
    pygame.draw.rect(screen, (90, 200, 120), player)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

音效与游戏体验中的所有课

自己练习: Pygame 在线编辑器