def loadaudiofx(self): self.blockfx = { 'j': sdlmixer.Mix_LoadWAV(b"./res/audio/fx/j.wav"), 'i': sdlmixer.Mix_LoadWAV(b"./res/audio/fx/i.wav"), 'z': sdlmixer.Mix_LoadWAV(b"./res/audio/fx/z.wav"), 'l': sdlmixer.Mix_LoadWAV(b"./res/audio/fx/l.wav"), 'o': sdlmixer.Mix_LoadWAV(b"./res/audio/fx/o.wav"), 't': sdlmixer.Mix_LoadWAV(b"./res/audio/fx/t.wav"), 's': sdlmixer.Mix_LoadWAV(b"./res/audio/fx/s.wav") } self.lockfx = sdlmixer.Mix_LoadWAV(b"./res/audio/fx/lock.wav") self.dropfx = sdlmixer.Mix_LoadWAV(b"./res/audio/fx/drop.wav") self.erasefx = sdlmixer.Mix_LoadWAV(b"./res/audio/fx/erase.wav")
def __init__(self, path): '''Load the sound file *Parameters:* - `path`: Path to the sound file ''' self.sample = mixer.Mix_LoadWAV(byteify(path, "utf-8")) if not self.sample: msg = "Cannot load file %s" % path logger.error(msg) raise SoundError(msg)
def loadSound(self, file): # find if this file has been loaded before and return that if so filepath = os.path.abspath(file) for index, sound in enumerate(self.sounds): if sound.path == filepath: return index # haven't seen this file before so add it and return new index index = self._getNextEmptySlot() try: sample = sdlmixer.Mix_LoadWAV( sdl2.ext.compat.byteify(filepath, "utf-8")) if sample is None: raise RuntimeError("Cannot open audio file: {}".format( sdlmixer.Mix_GetError())) self.sounds[index] = Sample(filepath, sample) except Exception as e: log(f"Problem loading sound: {str(e)} file: {filepath}") return len(self.sounds) - 1
def _load_chunk(self, fs_path): chunk = sdlmixer.Mix_LoadWAV(fs_path.encode("utf-8")) wave_file = wave.open(fs_path) duration = wave_file.getnframes() / wave_file.getframerate() self.chunks[fs_path] = chunk_tuple(chunk, duration) return self.chunks[fs_path]
def main(): #cause I don't want to pass these around global REN, SPRITE_FACTORY, SPRITE_RENDERER global CLICKEDBUTTON, BEEP1, BEEP2, BEEP3, BEEP4 sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO|sdl2.SDL_INIT_AUDIO) window = sdl2.ext.Window("Simulate", size=(WINDOWWIDTH, WINDOWHEIGHT)) REN = sdl2.ext.Renderer(window) REN.blendmode = sdl2.SDL_BLENDMODE_BLEND window.show() font_file = sysfont.get_font("freesans", sysfont.STYLE_BOLD) font_manager = sdl2.ext.FontManager(font_file, size=16) #fontmanager=font_manager will be default_args passed to every sprite creation method SPRITE_FACTORY = sdl2.ext.SpriteFactory(renderer=REN, fontmanager=font_manager, free=True) SPRITE_RENDERER = SPRITE_FACTORY.create_sprite_render_system(window) sdlmixer.Mix_Init(sdlmixer.MIX_INIT_OGG) sdlmixer.Mix_OpenAudio(44100, sdlmixer.MIX_DEFAULT_FORMAT, 2, 1024) BEEP1 = sdlmixer.Mix_LoadWAV(b"beep1.ogg") BEEP2 = sdlmixer.Mix_LoadWAV(b"beep2.ogg") BEEP3 = sdlmixer.Mix_LoadWAV(b"beep3.ogg") BEEP4 = sdlmixer.Mix_LoadWAV(b"beep4.ogg") #channel = sdlmixer.Mix_PlayChannel(-1, BEEP1, 0) # Initialize some variables for a new game pattern = [] # stores the pattern of colors currentStep = 0 # the color the player must push next lastClickTime = 0 # timestamp of the player's last button push score = 0 # when False, the pattern is playing. when True, waiting for the player to click a colored button: waitingForInput = False #directions text sprite info_text = make_text(SPRITE_FACTORY, "Match the pattern by clicking on the button or using the Q, W, A, S keys.", 10, WINDOWHEIGHT-25) CLICKEDBUTTON = [] while True: REN.fill((0, 0, WINDOWWIDTH, WINDOWHEIGHT), BGCOLOR) drawButtons() score_text = make_text(SPRITE_FACTORY, "Score: "+str(score), WINDOWWIDTH - 100, 10) SPRITE_RENDERER.render([score_text, info_text]) handle_events() if not waitingForInput: # play the pattern sdl2.SDL_Delay(1000) pattern.append(random.choice((YELLOW, BLUE, RED, GREEN))) for button in pattern: handle_events() flashButtonAnimation(button) sdl2.SDL_Delay(FLASHDELAY) waitingForInput = True else: # wait for the player to enter buttons if CLICKEDBUTTON and CLICKEDBUTTON[0] == pattern[currentStep]: # pushed the correct button flashButtonAnimation(CLICKEDBUTTON[0]) currentStep += 1 lastClickTime = sdl2.SDL_GetTicks() #could replace with collections.deque but premature optimizations and all that CLICKEDBUTTON.pop(0) if currentStep == len(pattern): # pushed the last button in the pattern changeBackgroundAnimation() score += 1 waitingForInput = False currentStep = 0 # reset back to first step #CLICKEDBUTTON.clear() clear added in 3.3! ... I'm surprised it hasn't been there forever since it's way better than del l[:] or l[:] = [] #and it parallels other collection clear functions del CLICKEDBUTTON[:] elif (CLICKEDBUTTON and CLICKEDBUTTON[0] != pattern[currentStep]) or (currentStep != 0 and sdl2.SDL_GetTicks() - TIMEOUT*1000 > lastClickTime): # pushed the incorrect button, or has timed out gameOverAnimation() # reset the variables for a new game: pattern = [] #CLICKEDBUTTON.clear() del CLICKEDBUTTON[:] currentStep = 0 waitingForInput = False score = 0 sdl2.SDL_Delay(1000) changeBackgroundAnimation() sdl2.SDL_Delay(1000//FPS) shutdown()
def register_sound(self, sound_filename): if sound_filename in self.sounds: return self.sounds[sound_filename] new_sound = sdlmixer.Mix_LoadWAV(bytes(sound_filename, 'utf-8')) self.sounds[sound_filename] = new_sound return new_sound
if __name__ == "__main__": RESOURCES = sdl2.ext.Resources(__file__, "") # Audio if sdl2.SDL_Init(sdl2.SDL_INIT_AUDIO) != 0: raise RuntimeError("Cannot initialize audio system: {}".format( sdl2.SDL_GetError())) # int Mix_OpenAudio(int frequency, Uint16 format, int channels, int chunksize) if sdlmixer.Mix_OpenAudio(44100, sdlmixer.MIX_DEFAULT_FORMAT, 2, 1024): raise RuntimeError("Cannot open mixed audio: {}".format( sdlmixer.Mix_GetError())) sdlmixer.Mix_AllocateChannels(64) sound_file = RESOURCES.get_path("Cat.wav") sample = sdlmixer.Mix_LoadWAV(sdl2.ext.compat.byteify(sound_file, "utf-8")) if sample is None: raise RuntimeError("Cannot open audio file: {}".format( sdlmixer.Mix_GetError())) count = 5 while count > 0: channel = sdlmixer.Mix_PlayChannel(channel=-1, chunk=sample, loops=0) sdlmixer.Mix_SetPosition(channel, 270, 100) print(channel) if channel == -1: raise RuntimeError("Cannot play sample: {}".format( sdlmixer.Mix_GetError())) # while sdlmixer.Mix_Playing(channel): sdl2.SDL_Delay(800)