def test_set_error(self): self.assertEqual(pygame.get_error(), "") pygame.set_error("hi") self.assertEqual(pygame.get_error(), "hi") pygame.set_error("") self.assertEqual(pygame.get_error(), "")
def test_get_error(self): # __doc__ (as of 2008-08-02) for pygame.base.get_error: # pygame.get_error(): return errorstr # get the current error message # # SDL maintains an internal error message. This message will usually # be given to you when pygame.error is raised. You will rarely need to # call this function. # e = pygame.get_error() self.assertTrue(e == "" or # This may be returned by SDL_mixer built with # FluidSynth support. Setting environment variable # SDL_SOUNDFONTS to the path of a valid sound font # file removes the error message. e == "No SoundFonts have been requested" or e.startswith("Failed to access the SoundFont"), e) pygame.set_error("hi") self.assertEqual(pygame.get_error(), "hi") pygame.set_error("") self.assertEqual(pygame.get_error(), "")
def test_set_error(self): # The first error could be all sorts of nonsense or empty. e = pygame.get_error() pygame.set_error("hi") self.assertEqual(pygame.get_error(), "hi") pygame.set_error("") self.assertEqual(pygame.get_error(), "")
def __init__(self, __iconname): pygame.sprite.DirtySprite.__init__(self) try: self.image = pygame.image.load(os.path.join("icons", __iconname)).convert_alpha() except: print "Unable to load button icon %s" % (__iconname) print pygame.get_error() self.image = pygame.Surface((Button.TILE_SIZE, Button.TILE_SIZE)) self.fill = (0,0,0,0) self.rect = self.image.get_rect()
def test_set_error(self): e = pygame.get_error() self.assertTrue(e == "" or # This may be returned by SDL_mixer built with # FluidSynth support. Setting environment variable # SDL_SOUNDFONTS to the path of a valid sf2 file # removes the error message. e == "No SoundFonts have been requested", e) pygame.set_error("hi") self.assertEqual(pygame.get_error(), "hi") pygame.set_error("") self.assertEqual(pygame.get_error(), "")
def load_image(file): file = os.path.join(main_dir, 'data', file) try: surface = pygame.image.load(file) except pygame.error: raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error())) return surface
def pg_play_music(music_file, volume=0.8): """ stream music with mixer.music module in blocking manner this will stream the sound from disk while playing """ # set up the mixer freq = 44100 # audio CD quality bitsize = -16 # unsigned 16 bit channels = 2 # 1 is mono, 2 is stereo buffer = 2048 # number of samples (experiment for good sound) pg.mixer.init(freq, bitsize, channels, buffer) pg.mixer.music.set_volume(volume) clock = pg.time.Clock() try: pg.mixer.music.load(music_file) print("Playing file %s" % music_file) except pg.error: print("File %s not found! (%s)" % \ (music_file, pg.get_error())) return pg.mixer.music.play() # check if playback has finished while pg.mixer.music.get_busy(): clock.tick(30)
def play_music(music_file): freq = 44100 # audio CD quality= bitsize = -16 # unsigned 16 bit channels = 2 # 1 is mono, 2 is stereo buffer = 1024 # number of samples pygame.mixer.init(freq, bitsize, channels, buffer) # optional volume 0 to 1.0 try: pygame.mixer.music.set_volume(0.8) clock = pygame.time.Clock() try: pygame.mixer.music.load(music_file) print ("\nMusic file %s loaded!" % music_file) except pygame.error: print ("File %s not found! (%s)" % (music_file, pygame.get_error()) ) return pygame.mixer.music.play() print("\nPlaying Music ... ") while pygame.mixer.music.get_busy(): # check if playback has finished clock.tick(30) print("Done playing!") except KeyboardInterrupt: # if user hits Ctrl/C then exit # (works only in console mode) pygame.mixer.music.fadeout(1000) pygame.mixer.music.stop() raise SystemExit
def loadImage(file, alpha=True): file = os.path.join('media', file) try: surface = pygame.image.load(file) except pygame.error: raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error()) return surface.convert_alpha() if alpha else surface
def play_midi(music_file): """ " stream music with mixer.music module in blocking manner " this will stream the sound from disk while playing """ #===== Initiate mixer =====# freq = 44100 # audio CD quality bitsize = -16 # unsigned 16 bit channels = 2 # 1 is mono, 2 is stereo buffer = 1024 # number of samples pygame.mixer.init(freq, bitsize, channels, buffer) pygame.mixer.music.set_volume(1.0) clock = pygame.time.Clock() try: pygame.mixer.music.load(music_file) # print "Music file %s loaded!" % music_file except pygame.error: print "File %s not found! (%s)" % (music_file, pygame.get_error()) return pygame.mixer.music.play() while pygame.mixer.music.get_busy(): # check if playback has finished clock.tick(30)
def load_images_pattern(file_pattern, scale = 1): file_pattern = os.path.join(Globals.ART_DIR, file_pattern) file_list = glob.glob(file_pattern) #print file_pattern if not file_list: print "No file list from pattern" return image_list = [] for file in file_list: #print file try: surface = pygame.image.load(file) except pygame.error: raise SystemExit, 'Could not load image "%s" %s' % (file, pygame.get_error()) if scale > 1: surface = pygame.transform.scale(surface, (surface.get_width()*scale, surface.get_height()*scale)) img = surface.convert_alpha() image_list.append(img) if 0 == len(image_list): print "Error no image list" #print image_list return image_list
def load_font(f,size=30): f = os.path.join('res', f) try: font = pygame.font.Font(f,size) except pygame.error: raise SystemExit, 'Could not load font "%s" %s'%(file, pygame.get_error()) return font
def stop(self): try: pygame.mixer.music.stop() except pygame.error: prettyprint(COLORS.RED, 'Could not stop player! (%s)' % pygame.get_error()) raise self.playing = False
def build(self): """Called before the game loop starts.""" self.setup_cars() self.setup_finish_line() self.setup_event_handlers() self.setup_hud() # Load the background and scale to screen size. self.background = pygame.image.load('street.png') self.background = pygame.transform.scale(self.background, self.scr_surf.get_size()) # Set the delay before a key starts repeating, and the repeat rate. pygame.key.set_repeat(250, 25) self.hud.flash("Press G to start, R to reset", 2500) try: self.sounds['race_start'] = pygame.mixer.Sound(file='gunshot.ogg') self.sounds['race_end'] = pygame.mixer.Sound(file='winner.ogg') except pygame.error: print('Error loading sounds: {}'.format(pygame.get_error())) exit(1) if self.logging_enabled: import logging logging.info('Game done building.')
def play_sound(word, volume=0.8): """ stream music with mixer.music module in a blocking manner this will stream the sound from disk while playing """ path_file = 'audio/{word}.mp3'.format(word=word) # playsound.playsound('audio/{word}.mp3'.format(word=word), True) # set up the mixer freq = 44100 # audio CD quality bitsize = -16 # unsigned 16 bit channels = 2 # 1 is mono, 2 is stereo buffer = 2048 # number of samples (experiment to get best sound) pg.mixer.init(freq, bitsize, channels, buffer) # volume value 0.0 to 1.0 pg.mixer.music.set_volume(volume) clock = pg.time.Clock() try: pg.mixer.music.load(path_file) print("Music file {} loaded!".format(path_file)) except pg.error: print("File {} not found! ({})".format(path_file, pg.get_error())) return pg.mixer.music.play() while pg.mixer.music.get_busy(): # check if playback has finished clock.tick(30)
def loadImages(file_pattern, ObjType): file_pattern = os.path.join(Globals.ART_DIR, file_pattern) ObjType.file_name_list = glob.glob(file_pattern) #print file_pattern if not ObjType.file_name_list: raise SystemExit, "No file list from pattern '%s'" % file_pattern return ObjType.image_list = [] for file in ObjType.file_name_list: #print file try: surface = pygame.image.load(file) except pygame.error: raise SystemExit, 'Could not load image "%s" %s' % (file, pygame.get_error()) if ObjType.scale > 1: surface = pygame.transform.scale(surface, (surface.get_width()*ObjType.scale, surface.get_height()*ObjType.scale)) img = surface.convert_alpha() ObjType.image_list.append(img) ObjType.num_images = len(ObjType.image_list) if 0 == ObjType.num_images: raise SystemExit, "Error no image list"
def _(name, transparent=transparent): try: surface = pygame.image.load(name) except pygame.error: raise GamesError( 'Could not load animation frame "%s": %s' % (name, pygame.get_error()) ) if transparent: surface.set_colorkey(surface.get_at((0,0)), RLEACCEL) return surface.convert()
def loadresources(self): """painting on the surface (once) and create sprites""" # make an interesting background draw_examples(self.background) # background artwork try: # ----------- load sprite images ----------- PygView.images.append(pygame.image.load(os.path.join("data", "babytux.png"))) # index 0 # load other resources here except: print("pygame error:", pygame.get_error()) print("please make sure there is a subfolder 'data' and in it a file 'babytux.png'") pygame.quit() sys.exit() # ------- create (pygame) Sprites Groups and Sprites ------------- self.allgroup = pygame.sprite.LayeredUpdates() # for drawing self.ballgroup = pygame.sprite.Group() # for collision detection etc. self.hitpointbargroup = pygame.sprite.Group() self.bulletgroup = pygame.sprite.Group() self.tuxgroup = pygame.sprite.Group() self.enemygroup = pygame.sprite.Group() # ----- assign Sprite class to sprite Groups ------- Tux.groups = self.allgroup, self.tuxgroup Hitpointbar.groups = self.hitpointbargroup Ball.groups = self.allgroup, self.ballgroup Evildoge.groups = self.enemygroup, self.allgroup Bullet.groups = self.allgroup, self.bulletgroup self.ball1 = Ball(x=100, y=100) # creating a Ball Sprite self.ball2 = Ball(x=200, y=100) # create another Ball Sprite self.tux1 = Tux(x=400, y=200, dx=0, dy=0, layer=5, imagenr = 0) # over balls layer
def do_load(self, callback): if self.file_name.endswith('.dmd'): self.image_surface = ( mpf.media_controller.display_modules.dmd.load_dmd_file( file_name=self.file_name, palette=dmd_palette, alpha_color=self.alpha_color)) self.image_surface = self.image_surface[0] self.loaded = True else: # image file (.png, .bmp, etc.) try: self.image_surface = pygame.image.load(self.file_name) except pygame.error: self.asset_manager.log.error("Pygame Error for file %s. '%s'", self.file_name, pygame.get_error()) except: raise if self.target == 'dmd': # This image will be shown on the DMD, so we need to convert its # surface to the DMD format self.image_surface = ( mpf.media_controller.display_modules.dmd.surface_to_dmd( surface=self.image_surface, alpha_color=self.alpha_color)) # todo add shades here if we ever support values other than 16 self.loaded = True if callback: callback()
def get_image_surface(sprite_name): global _images if sprite_name not in SPRITE: return None if sprite_name in _images: return _images[sprite_name] cfg = SPRITE[sprite_name] fname = os.path.join(IMGDIR, cfg["file"]) try: surface = pygame.image.load(fname).convert_alpha() except pygame.error: raise SystemExit("Load img error %s %s"%(fname, pygame.get_error())) _images[sprite_name] = {"surface": surface} nx, ny = cfg["matrix"] sizex, sizey = cfg["size"] index = 0 for m in xrange(ny): y = sizey * m for n in xrange(nx): x = sizex * n subimg = surface.subsurface(pygame.Rect((x, y), (sizex, sizey))) _images[sprite_name][index] = subimg index += 1 return _images[sprite_name]
def fatalError(self, msg): """ In case of critical errors, this function is called to gracefully shut down the application and print an error message """ print(self.strings["error"]) print(msg + ": " + pygame.get_error()) pygame.quit() sys.exit()
def startFile(filename): # Make sure we catch any errors from pygame try: pygame.mixer.music.load(filename) pygame.mixer.music.play() gLogger.info("Playing %s" % (filename)) except pygame.error: gLogger.error("Error playing file %s: %s" % (filename, pygame.get_error()))
def load_sound(file): "loads a sound" try: sound = mixer.Sound(filepath(file)) except pygame.error: raise SystemExit('Could not load sound "%s" %s' % (file, pygame.get_error())) return sound
def test_get_error(self): # __doc__ (as of 2008-08-02) for pygame.base.get_error: # pygame.get_error(): return errorstr # get the current error message # # SDL maintains an internal error message. This message will usually # be given to you when pygame.error is raised. You will rarely need to # call this function. # self.assertEqual(pygame.get_error(), "") pygame.set_error("hi") self.assertEqual(pygame.get_error(), "hi") pygame.set_error("") self.assertEqual(pygame.get_error(), "")
def load_music(file): "loads music" try: music = mixer.music.load(filepath(file)) except pygame.error: raise SystemExit('Could not load music "%s" %s' % (file, pygame.get_error())) return music
def load_image (img_path): """Patch load image to not call surface.convert""" try: surface = pygame.image.load(img_path) except pygame.error: raise SystemExit('Could not load image "%s" %s'% (img_path, pygame.get_error())) return surface
def load_image(file): "loads an image, prepares it for play" file = os.path.join(GAME_DIR, 'data', file) try: surface = pygame.image.load(file) except pygame.error: raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error())) return surface.convert_alpha() #To blend in the border pixels
def load_image(file): "loads an image, prepares it for play" file = get_media_path(file) try: surface = pygame.image.load(file) except pygame.error: raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error()) return surface
def load_image(file): "loads an image, prepares it for play" file = os.path.join('data', file) try: surface = pygame.image.load(file) except pygame.error: raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error()) return surface.convert()
def load_image(fn): "loads an image, prepares it for play" fn = os.path.join(main_dir, 'BlocBreaker', fn) try: surface = pygame.image.load(fn) except pygame.error: raise SystemExit('Could not load image "%s" %s'%(fn, pygame.get_error())) return surface.convert()
def play_music(music_file): """ stream music with mixer.music module in blocking manner this will stream the sound from disk while playing """ clock = pygame.time.Clock() try: pygame.mixer.music.load(music_file) print "Music file %s loaded!" % music_file except pygame.error: print "File %s not found! (%s)" % (music_file, pygame.get_error()) return pygame.mixer.music.play() while pygame.mixer.music.get_busy(): # check if playback has finished clock.tick(30)
def play_music(music_file): """ stream music with mixer.music module in blocking manner this will stream the sound from disk while playing """ clock = pygame.time.Clock() #try-catch for playing audio from MIDI file try: pygame.mixer.music.load(music_file) print "Music file %s loaded!" % music_file self.update() except pygame.error: print "File %s not found! (%s)" % (music_file, pygame.get_error()) return pygame.mixer.music.play() #plays MIDI file self.update() #updates frame
def load_background(file, colorkey=-1): """loads an image, prepares it for play colourkey = -1 forces the left-top pixel colour to be transparent, use colourkey = None for non transparant surfaces """ file = os.path.join('Backgrounds', file) try: surface = pygame.image.load(file) except pygame.error: raise SystemExit, 'Could not load image "%s" %s' % (file, pygame.get_error()) surface = surface.convert() if colorkey is not None: if colorkey is -1: colorkey = surface.get_at((0, 0)) surface.set_colorkey(colorkey, RLEACCEL) return surface
def play_music(self, music_file): #while pg.mixer.music.get_busy() == True : # Clock().tick(10) try: sound = pg.mixer.Sound(music_file) sound.play(0) #pg.mixer.music.load(music_file) print("Music file {} loaded!".format(music_file)) except pg.error: print("File {} not found! {}".format(music_file, pg.get_error())) return #pg.mixer.music.play(0) #pg.event.wait() print(1)
def play_music(music_file): ''' stream music with mixer.music module in blocking manner this will stream the sound from disk while playing ''' clock = pygame.time.Clock() try: pygame.mixer.music.load(music_file) print("Music file {} loaded!".format(music_file)) except pygame.error: print("File {} not found! {}".format(music_file, pygame.get_error())) return pygame.mixer.music.play() # check if playback has finished while pygame.mixer.music.get_busy(): clock.tick(30)
def export_as_wav(midi_path, wav_path): sample_rate = 44100 # Sample rate used for WAV/MP3 channels = 2 # Audio channels (1 = mono, 2 = stereo) buffer = 1024 # Audio buffer size input_device = 2 # Which recording device to use. On my system Stereo Mix = 1 bitsize = -16 # unsigned 16 bit pygame.mixer.init(sample_rate, bitsize, channels, buffer) # optional volume 0 to 1.0 pygame.mixer.music.set_volume(1.0) # Init pyAudio format = pyaudio.paInt16 audio = pyaudio.PyAudio() stream = audio.open(format=format, channels=channels, rate=sample_rate, input=True, input_device_index=input_device, frames_per_buffer=buffer) try: pygame.mixer.music.load(midi_path) except pygame.error: print("Couldn't play %s! (%s)" % (midi_path, pygame.get_error())) return pygame.mixer.music.play() frames = [] # Record frames while the song is playing while pygame.mixer.music.get_busy(): frames.append(stream.read(buffer)) # Stop recording stream.stop_stream() stream.close() audio.terminate() wave_file = wave.open(wav_path, 'wb') wave_file.setnchannels(channels) wave_file.setsampwidth(audio.get_sample_size(format)) wave_file.setframerate(sample_rate) wave_file.writeframes(b''.join(frames)) wave_file.close()
def load_image(name, transparent): diretorio = main_dir.replace("cgd", "") path = os.path.join(diretorio, 'dados/imagens/', name) print(path) try: surface = pygame.image.load(path) except pygame.error: raise SystemExit('Nao foi possivel carregar a imagem %s %s ' % (path, pygame.get_error())) if transparent: corner = surface.get_at((0, 0)) surface.set_colorkey(corner, pygame.RLEACCEL) print(surface) return surface.convert()
def loadLevel(self): w, h = base.SCREEN_WIDTH, base.SCREEN_HEIGHT self.loadLevelGeometry() ## Load the images for the game try: self.loadLevelImages() except pygame.error: # get_error() returns SDL error msg raise ResourceException(pygame.get_error()) ## Run the codes on the map to spawn sprites self.run_codes(self.cdata, (0, 0, len(self.tlayer[0]), len(self.tlayer))) return True
def play_music(music_file): ''' stream music with mixer.music module in blocking manner this will stream the sound from disk while playing ''' global volume #clock = pg.time.Clock() try: pg.mixer.music.load(music_file) print("Music file {} loaded!".format(music_file)) except pygame.error: print("File {} not found! {}".format(music_file, pg.get_error())) return set_volume = float(volume) / float(255) set_volume = "{0:.1f}".format(set_volume) pg.mixer.music.set_volume(float(set_volume)) pg.mixer.music.play()
def play_sound(sound_file): """ Obtained from adafruit I2S decoder setup """ sound_file = "./uploads/" + sound_file clock = pg.time.Clock() try: pg.mixer.music.load(sound_file) print("Music file {} loaded!".format(sound_file)) except: print("File {} not found! {}".format(music_file, pg.get_error())) return pg.mixer.music.play() print("Now playing:", sound_file) audio = MP3(sound_file) return audio.info.length
def play_music(music_file, volume=0.8): freq = 44100 bitsize = -16 channels = 2 buffer = 2048 pg.mixer.init(freq, bitsize, channels, buffer) pg.mixer.music.set_volume(volume) clock = pg.time.Clock() try: pg.mixer.music.load(music_file) print("Music file {} loaded!".format(music_file)) except pg.error: print("File {} not found!".format(music_file, pg.get_error())) return pg.mixer.music.play() while pg.mixer.music.get_busy(): clock.tick(30)
def play_music(music_file): pygame.init() clock = pygame.time.Clock() try: pygame.mixer.music.load(music_file) print("Music file %s loaded!" % music_file) except pygame.error: print("File %s not found! (%s)" % (music_file, pygame.get_error())) return pygame.mixer.music.play() note_pitch_dict, notes = song_to_pitch_dict(music_file) """ DRAW WHILE PLAYING MUSIC""" wave(note_pitch_dict, notes) while pygame.mixer.music.get_busy(): # check if playback has finished clock.tick(30)
def play_music(music_file, volume=0.8): freq = 44100 # audio CD quality bitsize = -16 # unsigned 16 bit channels = 2 # 1 is mono, 2 is stereo buffer = 2048 # number of samples (experiment to get best sound) pg.mixer.init(freq, bitsize, channels, buffer) pg.mixer.music.set_volume(volume) clock = pg.time.Clock() try: pg.mixer.music.load(music_file) print("Music file {} loaded!".format(music_file)) except pg.error: print("File {} not found! ({})".format(music_file, pg.get_error())) return pg.mixer.music.play(-1)
def load_image(file, number): file = os.path.join('../res/image', file) try: surface = pygame.image.load(file).convert_alpha() except pygame.error: raise SystemExit('Could not load image \'%s\' %s' % (file, pygame.get_error())) width = surface.get_width() height = surface.get_height() if number == 0: return surface sub_width = int(width / number) print(sub_width, height) return [ surface.subsurface(Rect((i * sub_width, 0), (sub_width, height))) for i in range(number) ]
def _load_image(self, name, alpha, scale=1.0): """ load an image file and enable the transparency key""" name = os.path.join(self.data_folder, name) try: image = pg.image.load(name) if alpha: image = image.convert_alpha() else: image = image.convert() except pg.error: logging.error('Could not load image {}'.format(name)) raise SystemExit(pg.get_error()) rect = image.get_rect() if scale < 1.0: image = pg.transform.scale( image, (int(rect.w * scale), int(rect.h * scale))) return image
def display_text(self): """In dieser Funktion werden die metadata (inkl. Bilder) in das Fenster projeziert. Zuerst wird das Fenster mit der Hintergrundfarbe gefüllt, welche aus der Konfiguration geholt wird. Dann werden die Texte aufbereitet. Dies geschieht mit dem Font self.font und der Farbe aus self.fontColor - der Font selbst wird aber an anderer Stelle berechnet. Abhängig von der Anzahl der Bilder werden diese berechnet, skaliert und geschrieben.""" # Fenster initialisieren (mit Hintergrundfarbe füllen self._actScreen = None self.timerIndex = 0 self.diaShowPics = [] self.diaIndex = -1 self.diaShowPics.append(self.audioFile.getFrontCover()) try: g = CONFIG.gui[self.winState] logging.debug("going to fill the background to: {!s}".format(g.backgroundColor)) try: self.doFillBackground(self.screen, g.backgroundColor, True) except: print(pygame.get_error()) self.quit() logging.debug("going to get blit object... ") obj = self.getBlitObject() sorted_x = sorted(obj, key=operator.attrgetter('zIndex')) for o in sorted_x: self.doBlitObject(self.screen, o, True) except: logging.error("Error at blit-object %s " % (sys.exc_info()[0])) errorhandling.Error.show() self.quit() self._saveScreen = self.screen.copy() self._actScreen = self.screen.copy() if not self._resize: self.timerIndex = self._gstPlayer.queryPositionInMilliseconds() / 1000 if not self._resize: self.audioFile.loadPictures() self.diaShowPics = self.audioFile.getAllPics() self._resize = False return
def play_music(self, music_file): """ stream music with mixer.music module in blocking manner this will stream the sound from disk while playing Referenced: https://www.daniweb.com/programming/software-development/code/216976/play-a-midi-music-file-using-pygame """ clock = pygame.time.Clock() try: pygame.mixer.music.load(music_file) print("Music file %s loaded!" % music_file) except pygame.error: print("File %s not found! (%s)" % (music_file, pygame.get_error())) return pygame.mixer.music.play() while pygame.mixer.music.get_busy(): # check if playback has finished clock.tick(15)
def load_per_pixel(file: str) -> pygame.Surface: """ Not compatible with 8 bit depth color surface""" assert isinstance( file, str), 'Expecting path for argument <file> got %s: ' % type(file) try: surface = pygame.image.load(file) buffer_ = surface.get_view('2') w, h = surface.get_size() source_array = frombuffer(buffer_, dtype=uint8).reshape((w, h, 4)) surface_ = pygame.image.frombuffer(source_array.copy(order='C'), (tuple(source_array.shape[:2])), 'RGBA').convert_alpha() return surface_ except pygame.error: raise SystemExit('\n[-] Error : Could not load image %s %s ' % (file, pygame.get_error()))
def play_audio(music_file): clock = pg.time.Clock() try: pg.mixer.music.load(music_file) print("Music file {} loaded!".format(music_file)) except pg.error: print("File {} not found! {}".format(music_file, pg.get_error())) return pg.mixer.music.play() #fade in to remove cracking for x in range(0, 100): pg.mixer.music.set_volume(float(x) / 100.0) time.sleep(.0075) while pg.mixer.music.get_busy(): clock.tick(30)
def load_image(file=None, width=None, number=18): # file = os.path.join(MAIN_DIR, 'data/image', file) file = "D:/Projects/Python/3.5.2/PlantsVSZombies/src/_0008_shujing.png" try: # surface = pygame.image.load(file).convert_alpha() surface = pygame.image.load(file) except pygame.error: raise SystemExit('Could not load image "%s" %s' % (file, pygame.get_error())) if width == None: return surface height = surface.get_height() return [ surface.subsurface(Rect((i * width, 0), (width, height))) for i in range(number) ]
def load_image(filename, transparent=True): """Loads an image, prepares it for play. Returns a pygame.Surface object which you can give as the "image" parameter to Sprite. filename -- the filename of the image to load transparent -- whether the background of the image should be transparent. Defaults to true. The background color is taken as the color of the pixel at (0,0) in the image. """ try: surface = pygame.image.load(filename) except pygame.error: raise GamesError( 'Could not load image "%s" %s'%(filename, pygame.get_error()) ) if transparent: corner = surface.get_at((0, 0)) surface.set_colorkey(corner, RLEACCEL) return surface.convert()
def loadresources(self): """painting on the surface (once) and create sprites""" # make an interesting background #draw_examples(self.background) # background artwork try: # ----------- load sprite images ----------- tile = pygame.image.load(os.path.join("data", "startile-300px.png")) # tile = pygame.transform.scale(tile, (100,100)) # scale tile to (pixel): x=100, y=100 PygView.images.append(pygame.image.load(os.path.join("data", "babytux.png"))) # index 0 PygView.images.append(pygame.image.load(os.path.join("data", "babytux_neg.png"))) # index 1 # PygView.images.append(pygame.image.load(os.path.join("data", "babytux_neg.png"))) # index 2 # load other resources here except: print("pygame error:", pygame.get_error()) print("please make sure there is a subfolder 'data' with the resource files in it") pygame.quit() sys.exit() # fill background with tiles self.background = fill_surface_with_tiles(tile, self.width, self.height) self.worldbackground = fill_surface_with_tiles(tile, self.worldwidth, self.worldheight) # write text # ------- write text over everything ----------------- write(self.background, "Press b to add another ball", x=self.width // 2, y=250, center=True) # write(self.background, "Press c to add another bullet", x=self.width//2, y=275, center=True) write(self.background, "Press w,a,s,d or i,j,k,l to steer tux", x=self.width // 2, y=300, center=True) write(self.background, "Press space or LCTRL to fire from tux", x=self.width // 2, y=325, center=True) self.paintgrid() # ------- create (pygame) Sprites Groups and Sprites ------------- self.allgroup = pygame.sprite.LayeredUpdates() # for drawing self.ballgroup = pygame.sprite.Group() # for collision detection etc. self.hitpointbargroup = pygame.sprite.Group() self.bulletgroup = pygame.sprite.Group() self.fire_at_player_group = pygame.sprite.Group() self.tuxgroup = pygame.sprite.Group() # ----- assign Sprite class to sprite Groups ------- Tux.groups = self.allgroup, self.tuxgroup Hitpointbar.groups = self.hitpointbargroup Ball.groups = self.allgroup, self.ballgroup, self.fire_at_player_group # each Ball object belong to those groups Bullet.groups = self.allgroup, self.bulletgroup self.tux1 = Tux(x=200, y=200, dx=0, dy=0, layer=5, imagenr=0) # FlyingObject number 1 self.tux2 = Tux(x=400, y=200, dx=0, dy=0, layer=5, imagenr=1) # FlyingObject number 2 self.ball1 = Ball(x=100, y=100, radius=10) # FlyingObject number 3 self.ball2 = Ball(x=200, y=100, radius=20) # FlyingObject number 3
def play_midi_from_file(midi_file_path='', multitrack=None, vol=1.0): """ midi_file_path: path to midi file on disc multitrack: pypianoroll style multitrack instance that can be written to file vol: How loudly to play, from 0.0 to 1.0 Play back midi data over computer audio by reading from file on disk or a pypianoroll multitrack instance. """ midi_file = midi_file_path pygame.mixer.init(frequency=44100, size=-16, channels=1, buffer=1024) pygame.mixer.music.set_volume(vol) with tempfile.TemporaryFile() as temporary_midi_file: if midi_file_path == '': multitrack.to_pretty_midi().write(temporary_midi_file) temporary_midi_file.seek(0) midi_file = temporary_midi_file try: clock = pygame.time.Clock() try: pygame.mixer.music.load(midi_file) except pygame.error: print( "File {file_path} not found:".format( file_path=midi_file_path), pygame.get_error()) return pygame.mixer.music.play() while pygame.mixer.music.get_busy(): clock.tick(30) except KeyboardInterrupt: pygame.mixer.music.fadeout(1000) pygame.mixer.music.stop() raise SystemExit
def play_music_thread(self,sid): music_info = MusicData.get_music_info(self, sid) if not music_info: music_info = self.search_music_info(sid) else: self.music_info=music_info # play now clock = pygame.time.Clock() try: print self.music_info['path'] pygame.mixer.music.load(self.music_info['path']) print("Music file {} loaded!".format(self.music_info['path'])) except pygame.error: print("File {} error! {}".format(self.music_info['path'], pygame.get_error())) return pygame.mixer.music.play() while pygame.mixer.music.get_busy(): clock.tick(30) pass
def play_music(self, music_file): clock = pg.time.Clock() try: pg.mixer.music.set_volume(1.0) pg.mixer.music.load(music_file) #print("Music file {} loaded!".format(music_file)) except pygame.error: print("File {} not found! {}".format(music_file, pg.get_error())) return pg.mixer.music.play() #print("eseguo " + format(music_file)) # If you want to fade in the audio... # for x in range(0,100): # pg.mixer.music.set_volume(float(x)/100.0) # time.sleep(.0075) # # check if playback has finished while pg.mixer.music.get_busy(): clock.tick(50)
def play_music(self): ''' Play music in self.midi_file. Arguments: -- self Return: None. ''' clock = pygame.time.Clock() try: pygame.mixer.music.load(self.midi_file) print("Music file", self.midi_file, " loaded!") except pygame.error: print("File ", self.midi_file, " not found! (", pygame.get_error(), ")") return pygame.mixer.music.play() while pygame.mixer.music.get_busy(): clock.tick(30)
def play(self, music_file, mem_loader=True): ''' stream music with mixer.music module in blocking manner this will stream the sound from disk while playing ''' try: if mem_loader: self.load_to_mem(music_file) pygame.mixer.music.load(self.m) else: pygame.mixer.music.load(music_file) #print("Music file {} loaded!".format(music_file)) except pygame.error: print("File {} not found! {}".format(music_file, pygame.get_error())) return pygame.mixer.music.play(0) pygame.mixer.music.set_volume(0.5)
def play_music(music_file): import pygame freq = 44100 # audio CD quality bitsize = -16 # unsigned 16 bit channels = 2 # 1 is mono, 2 is stereo buffer = 1024 # number of samples pygame.mixer.init(freq, bitsize, channels, buffer) pygame.mixer.music.set_volume(0.8) clock = pygame.time.Clock() try: pygame.mixer.music.load(music_file) print("Music file %s loaded!" % music_file) except pygame.error: print("File %s not found! (%s)" % (music_file, pygame.get_error())) return pygame.mixer.music.play() while pygame.mixer.music.get_busy(): # check if playback has finished clock.tick(30) pygame.mixer.music.unload()
def play(self, file, pos=None): file = relDir + "/" + file try: self.q.load(file) print("Music file {} loaded!".format(file)) except pg.error: print("File {} not found! ({})".format(file, pg.get_error())) return try: self.q.set_pos(pos) except: print "Unable to set position" self.q.play() print "Playing now at: ", datetime.datetime.now().time() while self.q.get_busy(): pass print "Playing ended at: ", datetime.datetime.now().time()
def run(self): ''' stream music with mixer.music module in a blocking manner this will stream the sound from disk while playing ''' # set up the mixer self.freq = 44100 # audio CD quality self.bitsize = -16 # unsigned 16 bit self.channels = 2 # 1 is mono, 2 is stereo self.buffer = 2048 # number of samples (experiment to get best sound) pg.mixer.init(self.freq, self.bitsize, self.channels, self.buffer) # volume value 0.0 to 1.0 pg.mixer.music.set_volume(self.volume) clock = pg.time.Clock() try: pg.mixer.music.load(self.music) print("Music file {} loaded!".format(self.music)) except pg.error: print("File {} not found! ({})".format(self.music, pg.get_error())) return pg.mixer.music.play()