Menu
CoddyTech

소리 불러오기

Coddy Pygame 여정의 사운드와 게임의 손맛 섹션에 포함된 레슨. 23개 중 1번째.

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

챌린지

쉬움

Space를 누르면 초록색 사각형이 점프합니다. 소리를 재생하도록 해 보세요.

  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 플레이그라운드