728x90
반응형
SMALL

bgm.wav
5.62MB
gunsound.mp3
0.04MB

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

 

코드 설명

  • 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.6.0 documentation

Resets playback of the current music to the beginning. If pause() has previously 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.6.0 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