Aggiungi supporto per audio e migliora la gestione delle dipendenze nel progetto
This commit is contained in:
+46
-8
@@ -2,9 +2,12 @@ import os
|
||||
import sdl2
|
||||
import sdl2.ext
|
||||
from sdl2.ext.compat import byteify
|
||||
|
||||
from ctypes import *
|
||||
|
||||
from PIL import Image
|
||||
from sdl2 import SDL_AudioSpec
|
||||
|
||||
import random
|
||||
class GameWindow:
|
||||
def __init__(self, width, height, cell_size, title="Default", key_callback=None):
|
||||
|
||||
@@ -34,10 +37,15 @@ class GameWindow:
|
||||
self.running = True
|
||||
self.key_down, self.key_up, self.axis_scroll = key_callback
|
||||
self.performance = 0
|
||||
self.audio_devs = []
|
||||
for i in range(5):
|
||||
self.audio_devs.append((True, sdl2.SDL_OpenAudioDevice(None, 0, SDL_AudioSpec(freq=22050, aformat=sdl2.AUDIO_U8, channels=1, samples=2048), None, 0)))
|
||||
|
||||
|
||||
def load_joystick(self):
|
||||
sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
|
||||
sdl2.SDL_JoystickOpen(0)
|
||||
|
||||
|
||||
def generate_fonts(self,font_file):
|
||||
fonts = {}
|
||||
@@ -206,11 +214,41 @@ class GameWindow:
|
||||
self.h_offset = y
|
||||
|
||||
def play_sound(self, sound_file):
|
||||
print(sound_file)
|
||||
sound_file = os.path.join("sound", sound_file)
|
||||
rw = sdl2.SDL_RWFromFile(byteify(sound_file, "utf-8"), b"rb")
|
||||
if not rw:
|
||||
raise RuntimeError("Failed to open sound file")
|
||||
|
||||
_buf = POINTER(sdl2.Uint8)()
|
||||
_length = sdl2.Uint32()
|
||||
spec = SDL_AudioSpec(freq=22050, aformat=sdl2.AUDIO_U8, channels=1, samples=2048)
|
||||
|
||||
if sdl2.SDL_LoadWAV_RW(rw, 1, byref(spec), byref(_buf), byref(_length)) == None:
|
||||
raise RuntimeError("Failed to load WAV")
|
||||
devid = None
|
||||
while not devid:
|
||||
id = random.randint(0, 4)
|
||||
for idx, dev in enumerate(self.audio_devs):
|
||||
if dev[0]:
|
||||
devid = dev[1]
|
||||
sdl2.SDL_ClearQueuedAudio(devid)
|
||||
self.audio_devs[id] = (False, devid)
|
||||
break
|
||||
if not devid:
|
||||
|
||||
devid = self.audio_devs[id][1]
|
||||
sdl2.SDL_ClearQueuedAudio(devid)
|
||||
self.audio_devs[random.randint(0, 4)] = (True, devid)
|
||||
|
||||
# Start playing audio
|
||||
sdl2.SDL_QueueAudio(devid, _buf, _length)
|
||||
sdl2.SDL_PauseAudioDevice(devid, 0)
|
||||
|
||||
return
|
||||
sample = sdl2.sdlmixer.Mix_LoadWAV(byteify(sound_file, "utf-8"))
|
||||
if sample is None:
|
||||
raise RuntimeError("Cannot open audio file: {}".format(sdl2.sdlmixer.Mix_GetError()))
|
||||
channel = sdl2.sdlmixer.Mix_PlayChannel(-1, sample, 0)
|
||||
if channel == -1:
|
||||
print(f"Cannot play sound: {sdl2.sdlmixer.Mix_GetError()}")
|
||||
def stop_sound(self):
|
||||
for dev in self.audio_devs:
|
||||
if not dev[0]:
|
||||
sdl2.SDL_PauseAudioDevice(dev[1], 1)
|
||||
sdl2.SDL_ClearQueuedAudio(dev[1])
|
||||
dev[0] = True
|
||||
|
||||
|
||||
Reference in New Issue
Block a user