Pygame - 音效物件



使用音樂和音效可以使任何電腦遊戲更具吸引力。Pygame 庫透過 pygame.mixer 模組支援此功能。此模組包含 Sound 類,用於載入 Sound 物件和控制播放。所有聲音播放都在後臺執行緒中混合。為了減少延遲,請使用較小的緩衝區大小。

要從聲音檔案或檔案物件獲取 Sound 物件,請使用以下建構函式:

pygame.mixer.Sound(filename or file object)

Sound 類定義了以下方法來控制播放:

play(loops=0, maxtime=0, fade_ms=0) 在可用的通道上開始播放 Sound(即在電腦揚聲器上)。Loops 引數用於重複播放。
stop() 這將停止在任何活動通道上播放此 Sound。
fadeout(time) 這將在以毫秒為單位的時間引數內淡出後停止播放聲音。
set_volume(value) 這將設定此 Sound 的播放音量,如果正在播放,則會立即影響 Sound 以及此 Sound 的任何未來播放。音量範圍為 0.0 到 1.0。
get_length() 返回此 Sound 的長度(以秒為單位)。

在下面的示例中,一個文字按鈕渲染在顯示視窗的底部。空格鍵會向上發射一支箭,同時播放聲音。

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))

在遊戲事件迴圈中,對於檢測到的空格鍵,一個箭頭物件放置在 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()
廣告