728x90
반응형
SMALL
from tkinter import *
import pygame

class GameSound:
	def __init__(self):
		window = Tk() # 윈도우 생성
		window.title("게임사운드") # 제목을 설정
		window.geometry("640x480") # 윈도우 크기 설정
		window.resizable(0,0)        
		
		
		self.canvas = Canvas(window, bg = "white")
		self.canvas.pack(expand=True,fill=BOTH)
		window.bind("<KeyPress>",self.keyPressHandler)
		window.bind("<KeyRelease>",self.keyReleaseHandler)

		#pygame 에서 music vs sound
		# music: 배경음악 재생을 위해 사용
		# sound: 효과음을 위해 사용

        #BG sound.
		pygame.init()
		pygame.mixer.music.load("bgm.wav") #Loading File Into Mixer
		pygame.mixer.music.play(-1) #Playing It In The Whole Device
		self.canvas.create_text(320,400,font="Times 15 italic bold",text="Sound Example")

		#Effect sound
		self.sounds = pygame.mixer
		self.sounds.init()
		self.s_effect1 = self.sounds.Sound("gunsound.mp3")
				
		while True:
			#
			window.after(33)
			window.update()

	def keyReleaseHandler(self, event):
		if event.keycode in self.keys:
		    self.keys.remove(event.keycode)

	def keyPressHandler(self, event):		
		self.s_effect1.play()
		self.keys.add(event.keycode)

GameSound()

tkinter에서는 사운드와 관련된 클래스 및 함수를 제공하지 않습니다.  그래서 코드에서는 pygame 모듈을 이용하여 사운드 재생방법을 설명을 하도록 하겠습니다. (앞서 설명된 게임 기본 코드 구조 위에서 추가된 내용들만 설명)

 

사운드의 종류는 크게 기본적으로 배경사운드, 이펙트사운드로 구분될 수 있습니다. 배경사운드는 게임의 전체적인 분위기를 담당하고 이펙트 사운드는 그 순간의 효과 또는 느낌(타격감, 행위(점프, 스피드업, 아이템 획득), 죽음 등)을 담당하며, 사운드를 게임의 진행에 있어서 필수적인 요소입니다. 그래서 위 코드에서는 배경사운드와 이펙트사운드의 재생 방법에 대해서 설명하도록 하겠습니다.

 

pygame에서 사운드 재생 방법은 music와 sound 이렇게 2가지를 제공하고 있습니다.

차이점은 music의 경우 하나의 재생만 가능하고 만약 다른 파일을 load() 해서 재생하면 기존 재생은 멈추게 되며, 반대로 sound 는 여러 개가 동시 재생이 가능하고 같은 사운드의 중첩해서 재생도 가능합니다.

그리고 music의 경우 파일이 저장된 장치(ssd 또는 hard disk 등)에서 재생을 하지만 sound의 경우 파일 전체를 메모리에 가져온 후 재생하게 됩니다. 즉 music은 큰 용량을 가진 음악 파일 재생에 유리하며 sound의 경우 작은 용량과 짧은 사운드(이펙트)에 유리합니다.

그러므로 music의 경우 배경사운드에 이용되고 sound의 경우 이펙트사운드에 사용합니다.

 

위 소스에 대한 주요 코드 설명은 아래와 같습니다.

  • pygame 모듈을 사용하기 위해 pygame을 import 한다.(line 2)
  • pygame을 사용하기 위해서는 pygame.init()함수를 호출해야한다.(line 21)
  • 위 코드에서 music.load(), music.play() 함수를 이용하여 배경음악을 무한반복 재생한다.(line 22, 23)
  • effect sound를 위해 sounds 를 초기화 한다.(line 28)
  • 이펙트 사운드 'gunsound.mp3'  파일을 읽고 sound 객체를 반환한다. sound 객체는 이펙트 사운드는 게임중 재생 및 멈춤을 컨트롤할 수 있다.
  • line 41에서 이펙트 사운드를 재생한다.

위 코드만으로 간단히 게임에서 필요한 음악 재생은 가능하며 좀 더 다양한 기능을 구현하기 위해서는 아래의 링크를 참조하기 바랍니다.

 

 

https://www.pygame.org/docs/ref/music.html

 

pygame.mixer.music — pygame v2.1.1 documentation

Resets playback of the current music to the beginning. If pause() has previoulsy been used to pause the music, the music will remain paused. Note rewind() supports a limited number of file types and notably WAV files are NOT supported. For unsupported file

www.pygame.org

https://www.pygame.org/docs/ref/mixer.html

 

pygame.mixer — pygame v2.1.1 documentation

begin sound playback play(loops=0, maxtime=0, fade_ms=0) -> Channel Begin playback of the Sound (i.e., on the computer's speakers) on an available Channel. This will forcibly select a Channel, so playback may cut off a currently playing sound if necessary.

www.pygame.org

 

 

728x90
반응형
LIST

+ Recent posts