Pygameの勉強 *効果音とBGMの再生の巻*
ゲームに効果音は必須っしょ!!ってなことで、どうすれば効果音やBGMを再生することが出来るのか勉強しました。Pythonでゲーム作りますが何か?このサイトにとても良くまとめられているので参考にしています。
#! /usr/bin/env python # -*- coding -utf-8 -*- import pygame from pygame.locals import * import sys SCR_WIDTH,SCR_HEIGHT = 640,480 pygame.init() screen = pygame.display.set_mode((SCR_WIDTH,SCR_HEIGHT)) pygame.display.set_caption("sound test") #画像のロード backImg = pygame.image.load('grass.jpg').convert() Img = pygame.image.load('pythonImg.png').convert_alpha() Img_rect = Img.get_rect() #サウンドのロード sound = pygame.mixer.Sound('sound.wav') vx = vy = 300 #一秒間の移動ピクセル clock = pygame.time.Clock() #BGMを再生 pygame.mixer.music.load('bgm.mp3') pygame.mixer.music.play(-1) while True: time_pressed = clock.tick(60) time_pressed_seconds = time_pressed /1000.0 #ミリ秒を秒に変換 #画像の移動 Img_rect.x += vx * time_pressed_seconds Img_rect.y += vy * time_pressed_seconds #跳ね返り処理 if Img_rect.left < 0 or Img_rect.right > SCR_WIDTH: sound.play() #サウンドの再生 vx = -vx if Img_rect.top < 0 or Img_rect.bottom > SCR_HEIGHT: sound.play() #サウンドの再生 vy = -vy screen.blit(backImg,(0,0)) screen.blit(Img,Img_rect) pygame.display.update() #イベント処理 for event in pygame.event.get(): if event.type == QUIT: sys.exit() if event.type == KEYDOWN and event.key == K_ESCAPE: sys.exit()