コード例 #1
0
ファイル: base_test.py プロジェクト: AceZOfZSpades/RankPanda
    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(), "")
コード例 #2
0
ファイル: base_test.py プロジェクト: CTPUG/pygame_cffi
    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(), "")
コード例 #3
0
ファイル: base_test.py プロジェクト: Yarrcad/CPSC-386-Pong
    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(), "")
コード例 #4
0
	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()
コード例 #5
0
ファイル: base_test.py プロジェクト: Anugrahaa/anagrammatic
    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(), "")
コード例 #6
0
ファイル: main.py プロジェクト: AlexOteiza/Bomberman_Party
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
コード例 #7
0
ファイル: FoscamManager.py プロジェクト: lap089/FoscamManager
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)
コード例 #8
0
ファイル: playMidiFile.py プロジェクト: sookool99/Summer2015
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
コード例 #9
0
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
コード例 #10
0
ファイル: midiclass.py プロジェクト: ifbird/choir-metronome
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)
コード例 #11
0
ファイル: SpriteLib.py プロジェクト: stdarg/invaders
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
コード例 #12
0
ファイル: lib.py プロジェクト: shawnbow/dudu123
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
コード例 #13
0
ファイル: broadcast.py プロジェクト: bustardcelly/radiopi
 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
コード例 #14
0
ファイル: main.py プロジェクト: ZachMassia/pygame-labs
    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.')
コード例 #15
0
ファイル: play_audio.py プロジェクト: kn7072/kn7072
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)
コード例 #16
0
ファイル: SpriteLib.py プロジェクト: stdarg/invaders
    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"
コード例 #17
0
ファイル: games.py プロジェクト: CapitainCrunch/garbage
 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()
コード例 #18
0
ファイル: minirpg002.py プロジェクト: paolo-perfahl/mini_rpg
 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
コード例 #19
0
ファイル: image.py プロジェクト: HarryXS/mpf
    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()
コード例 #20
0
ファイル: res.py プロジェクト: fanlix/fish
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]
コード例 #21
0
ファイル: gameflow.py プロジェクト: rlv-dan/BubbleMath
	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()
コード例 #22
0
ファイル: soundPlayer.py プロジェクト: sizlo/RPiFun
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()))
コード例 #23
0
ファイル: game.py プロジェクト: telecoda/pyweek21
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
コード例 #24
0
ファイル: base_test.py プロジェクト: AceZOfZSpades/RankPanda
    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(), "")
コード例 #25
0
ファイル: game.py プロジェクト: telecoda/pyweek21
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
コード例 #26
0
ファイル: HelperPatch.py プロジェクト: andrewmains12/EmBall
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
コード例 #27
0
ファイル: game_loop.py プロジェクト: VKEDCO/PYPL
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
コード例 #28
0
ファイル: main.py プロジェクト: ducky007/Dandy-Dungeon
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
コード例 #29
0
ファイル: foo1.py プロジェクト: p-blomberg/yamosg
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()
コード例 #30
0
ファイル: BlocBreaker.py プロジェクト: YudaDiga/first-try
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()
コード例 #31
0
ファイル: py-midi.py プロジェクト: pedrojlsilva/IHS
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)
コード例 #32
0
ファイル: GUI.py プロジェクト: thebrianrichard/TrebleMaker
 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
コード例 #33
0
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
コード例 #34
0
    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)
コード例 #35
0
ファイル: MIDIplay.py プロジェクト: mk864mk864/ece5725
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)
コード例 #36
0
ファイル: audio_related.py プロジェクト: josephding23/RiffGAN
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()
コード例 #37
0
    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()
コード例 #38
0
ファイル: basegamelevel.py プロジェクト: allencch/Speckpater
    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
コード例 #39
0
ファイル: server_latest.py プロジェクト: chopper23/Cloud9Lite
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()
コード例 #40
0
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
コード例 #41
0
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)
コード例 #42
0
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)
コード例 #43
0
ファイル: putho.py プロジェクト: Amarakk/PuthoBeta
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)
コード例 #44
0
 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)
     ]
コード例 #45
0
ファイル: resources.py プロジェクト: Layto888/laylib
 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
コード例 #46
0
	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
コード例 #47
0
    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)
コード例 #48
0
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()))
コード例 #49
0
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)
コード例 #50
0
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)
    ]
コード例 #51
0
ファイル: games.py プロジェクト: MAXIMZOLOTYKH11/crimeg
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()
コード例 #52
0
    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
コード例 #53
0
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
コード例 #54
0
 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
コード例 #55
0
ファイル: tts_base.py プロジェクト: feniculiadmin/UallioEdu
    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)
コード例 #56
0
 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)
コード例 #57
0
ファイル: player.py プロジェクト: jason7830/railway_bot
    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)
コード例 #58
0
ファイル: main.py プロジェクト: maraoz/wiman
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()
コード例 #59
0
ファイル: music.py プロジェクト: shalini6/VisionAid
    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()
コード例 #60
0
ファイル: music.py プロジェクト: loic-michoud/Video-filter
 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()