示例#1
0
 def __init__(self, *args, **kwargs):
     super(self.__class__, self).__init__(*args, **kwargs)
     self.right = create_svg('ninja_right.svg')
     self.left = create_svg('ninja.svg')
     self.dead = create_svg('ninja_death.svg')
     self.sounds = [StaticSource(load('resources/sounds/ninja_hiya_1.ogg')),
                    StaticSource(load('resources/sounds/ninja_hiya_2.ogg'))]
示例#2
0
文件: resource.py 项目: einarf/pyglet
    def media(self, name, streaming=True):
        """Load a sound or video resource.

        The meaning of `streaming` is as for `media.load`.  Compressed
        sources cannot be streamed (that is, video and compressed audio
        cannot be streamed from a ZIP archive).

        :Parameters:
            `name` : str
                Filename of the media source to load.
            `streaming` : bool
                True if the source should be streamed from disk, False if
                it should be entirely decoded into memory immediately.

        :rtype: `media.Source`
        """
        self._require_index()
        from pyglet import media
        try:
            location = self._index[name]
            if isinstance(location, FileLocation):
                # Don't open the file if it's streamed from disk
                path = os.path.join(location.path, name)
                return media.load(path, streaming=streaming)
            else:
                file = location.open(name)
                return media.load(name, file=file, streaming=streaming)
        except KeyError:
            raise ResourceNotFoundException(name)
示例#3
0
    def media(self, name, streaming=True):
        '''Load a sound or video resource.

        The meaning of `streaming` is as for `media.load`.  Compressed
        sources cannot be streamed (that is, video and compressed audio
        cannot be streamed from a ZIP archive).

        :Parameters:
            `name` : str
                Filename of the media source to load.
            `streaming` : bool
                True if the source should be streamed from disk, False if
                it should be entirely decoded into memory immediately.

        :rtype: `media.Source`
        '''
        self._require_index()
        from pyglet import media
        try:
            location = self._index[name]
            if isinstance(location, FileLocation):
                # Don't open the file if it's streamed from disk -- AVbin
                # needs to do it.
                path = os.path.join(location.path, name)
                return media.load(path, streaming=streaming)
            else:
                file = location.open(name)
                return media.load(name, file=file, streaming=streaming)
        except KeyError:
            raise ResourceNotFoundException(name)
示例#4
0
def find_resource(type, filename):
    """return resource given type (e.g. RESOURCE_IMAGE) and filename"""

    path = os.path.join(path_for_resource_type(type), filename)

    if type == RESOURCE_IMAGE: return image.load(path)
    if type == RESOURCE_FONT:  return font.load(path)
    if type == RESOURCE_SOUND: return media.load(path, streaming=False)
    if type == RESOURCE_MUSIC: return media.load(path, streaming=True)

    assert False
示例#5
0
 def play_song(self):
     if self.track_number > 2:
         self.track_number = 1
     if self.track_number == 1:
         self.song = media.load("track_one.wav")
         self.music_player = self.song.play()
         self.next_song_time = self.current_time + 82
     elif self.track_number == 2:
         self.song = media.load("track_two.wav")
         self.music_player = self.song.play()
         self.next_song_time = self.current_time + 95
示例#6
0
def play(audio):
    if audio != "silent":
        player1 = Player()
        player1.queue(load(join(DATA, "chronotank.ogg")))
        player1.queue(load(join(DATA, "imagine_a_world.ogg")))
        player1.play()

        player2 = Player()
        player2.eos_action = Player.EOS_LOOP
        player2.queue(load(join(DATA, "stupidsongimadenofarting.ogg")))
        player2.play()
示例#7
0
 def load_source(self, filename):
     print 'loading source: ', filename
     self.source = media.load(filename)
     try:
         self.source = media.load(filename)
         print '1'
         self.width = int(self.source.video_format.width)
         self.height = int(self.source.video_format.height)
         self.duration = self.source.duration
         print 'loaded movie.. height: ', self.height, ' | width: ', self.width
     except:
         print 'failed to open movie!'
         ValueError('failed to open movie!')
示例#8
0
 def load_source(self, filename):
     print 'loading source: ', filename
     self.source = media.load(filename)
     try:
         self.source = media.load(filename)
         print '1'
         self.width = int(self.source.video_format.width)
         self.height = int(self.source.video_format.height)
         self.duration = self.source.duration
         print 'loaded movie.. height: ', self.height, ' | width: ', self.width
     except:
         print 'failed to open movie!'
         ValueError('failed to open movie!')
     self.calc_playback_rate()
示例#9
0
 def __init__(self):
     self.batch = Batch()
     self.background = Rectangle(0, 0, 0, 0)
     self.window = Window()
     self.window.push_handlers(self)
     self.on_resize(self.window.width, self.window.height)
     clock.schedule_interval(self.update, 1 / 60)
     clock.schedule_interval(self.log, 1)
     self.sounds = {
         'fail': media.load('resources/failure.mp3', streaming=False),
         'jump': media.load('resources/jump.wav', streaming=False),
         'score': media.load('resources/score.wav', streaming=False),
     }
     self.reset()
示例#10
0
def queueSoundtrack(song):
    global soundtrack
    if not soundtrack:
        soundtrack = media.Player()
        soundtrack.eos_action = 'loop'
    soundtrack.queue(media.load(os.path.join(data.data_dir, song)))
    return soundtrack
示例#11
0
 def __init__(self):
     Layer.__init__(self)
     self.config = Config()
     self.gallery = Gallery()
     self.schedule_interval(self.music_start, interval=7)
     self.intro_sound = load("music/sound_start.wav", streaming=False)
     self.intro_sound.play()
     self.is_event_handler = True
     background = Sprite(self.gallery.content["display"]["title"])
     self.optimal_scale = (
         self.config.window_width *
         self.display_pos_size["display_title"]["W"]) / background.width
     background.image_anchor = 0, 0
     background.scale = self.optimal_scale
     background.x = self.config.window_width * self.display_pos_size[
         "display_title"]["X"]
     background.y = self.config.window_height * self.display_pos_size[
         "display_title"]["Y"]
     self.left_margin = background.x
     self.bottom_margin = background.y
     self.optimal_width = background.width
     self.optimal_height = background.height
     self.add(background)
     place_holder_image = Sprite(self.gallery.content["screen"]["title"])
     place_holder_image.position = director.window.width / 2, director.window.height / 2
     place_holder_image.scale = self.optimal_scale
     place_holder_image.do(ScaleBy(5.2, duration=25))
     self.add(place_holder_image)
示例#12
0
文件: sound.py 项目: pdevine/suburbia
def queue_soundtrack(song='8bp069-06-she-streets.mp3', soundtrack=None):
    if not soundtrack:
        soundtrack = media.Player()
        soundtrack.eos_action = 'loop'

    soundtrack.queue(media.load(data_file(song)))
    return soundtrack
示例#13
0
def playSounds(instrument, notes, mutex, turnstile, turnstile2, counter):
	sound = media.load(instrument, streaming=False)
	pitch = 0
	for c in notes:
		mutex.acquire()
		counter.increment()
		if counter.get() == counter.getNum():
			turnstile2.acquire()
			turnstile.release()
		mutex.release()
		turnstile.acquire()
		turnstile.release()
		if c.isdigit():
			player = media.Player()
			player.queue(sound)
			player.pitch = (2.0**(float(c)/12))
			#player.pitch = int(c)
			#print player.pitch
			player.play()
			sleep(2)
		mutex.acquire()
		counter.decrement()
		if counter.get() == 0:
			turnstile.acquire()
			turnstile2.release()
		mutex.release()
		turnstile2.acquire()
		turnstile2.release()
示例#14
0
def get_mp3(text):
    text = text.replace(";", " beep ")
    text = text.translate(string.maketrans("", ""), string.punctuation)
    # text = text.replace(",", "")

    lowertext = text.lower()
    words = lowertext.split()
    player.queue(beep)
    for inword in words:
        try:
            word = int(inword)
        except:
            word = inword
        save_path = cwd + '\\tts_downloads\\{}.mp3'.format(word)
        if os.path.isfile(save_path) == False:
            # tts = gTTS(word, 'en-us')
            # tts.save(save_path)
            voicename = random.choice(vonavoices)
            pvoice.voice_name = voicename
            pvoice.fetch_voice(word, save_path)

        mp3 = media.load(save_path)
        player.queue(mp3)
    player.queue(beep)
    player.play()
    clock.schedule_interval(exit_callback, 1 / 10.0)
    app.run()
    print '\n' + text
示例#15
0
def play_sound_effect(name: str, volume: float = 1.0):
    """Play a sound effect."""
    player = Player()
    player.queue(load(f'{ASSETS}audio/{name}.wav'))
    player.volume = volume * settings.get_sfx_volume()
    player.play()
    sfxs.append(player)
示例#16
0
 def __init__(self,
              ec,
              file_name,
              pos=(0, 0),
              units='norm',
              scale=1.,
              center=True,
              visible=True):
     from pyglet.media import load, Player
     self._ec = ec
     self._source = load(file_name)
     self._player = Player()
     with warnings.catch_warnings(record=True):  # deprecated eos_action
         self._player.queue(self._source)
     self._player._audio_player = None
     frame_rate = self.frame_rate
     if frame_rate is None:
         logger.warning('Frame rate could not be determined')
         frame_rate = 60.
     self._dt = 1. / frame_rate
     self._texture = None
     self._playing = False
     self._finished = False
     self._pos = pos
     self._units = units
     self._center = center
     self.set_scale(scale)  # also calls set_pos
     self._visible = visible
示例#17
0
def queueSoundtrack(song):
    global soundtrack
    if not soundtrack:
        soundtrack = media.Player()
        soundtrack.eos_action = 'loop'
    soundtrack.queue(media.load(os.path.join(data.data_dir, song)))
    return soundtrack
示例#18
0
def tts1(text, lang):
    file = gTTS(text=text, lang=lang)
    filename = 'temp1.mp3'
    file.save(filename)

    src = media.load(filename)
    player = media.Player()
    player.queue(src)
    player.play()
    timeout = time.time() + src.duration
    while time.time() < timeout:
        r = sr.Recognizer()
        with sr.Microphone() as source:
            filename = 'beep.wav'
            music = pyglet.media.load(filename, streaming=False)
            music.play()
            time.sleep(music.duration)
            try:
                speech = r.listen(source, phrase_time_limit=4)
                text = r.recognize_google(speech)
                c = text.lower()
                if 'stop' in c:
                    player.pause()
                    player.next()
                    return
                else:
                    continue
            except Exception as e:
                pass
    player.pause()
    player.next()
    return
示例#19
0
def main():
    usage = '%prog [options] FILE'

    parser = OptionParser(usage)

    parser.add_option("--format", type='string', default=None)

    (options, args) = parser.parse_args()

    in_filename = args[0]

    if options.format is None or options.format.lower() != 'mono8':
        raise NotImplementedError('Only mono8 format is supported with no '
                                  'autodetection. Use "--format=mono8".')

    source = media.load(in_filename)
    imn, ts = get_frame(source)

    file_base = os.path.splitext(in_filename)[0]
    out_filename = file_base+'.fmf'

    fmf = fmf_mod.FlyMovieSaver(out_filename,
                                format='MONO8',
                                bits_per_pixel=8,
                                version=3,
                                )

    while imn is not None:
        fmf.add_frame( imn, ts )
        imn, ts = get_frame(source)
示例#20
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.wnd.mouse_exclusivity = False
        self.bpm = 242  # Hardcode bpm from info.dat
        self.camera = KeyboardCamera(self.wnd.keys,
                                     fov=60,
                                     near=1.0,
                                     far=1000.0)
        self.camera.velocity = 50
        self.camera_enabled = False

        meta = self.load_json('megalovania_remix/info.dat')
        self.map = BSScene(
            self.load_scene('bs_map3.glb'),
            self.camera,
            BSTrack('megalovania_remix/Expert.dat', meta['_beatsPerMinute']),
        )

        self.quad_fs = geometry.quad_fs()

        # Postprocess programs
        self.copy_prog = self.load_program('programs/copy.glsl')
        self.copy_greyscale_prog = self.load_program(
            'programs/copy_greyscale.glsl')
        self.blur_h_prog = self.load_program('programs/blur_h.glsl')
        self.blur_v_prog = self.load_program('programs/blur_v.glsl')
        self.combine = self.load_program('programs/combine.glsl')
        self.combine['texture1'] = 1

        # blur stuff
        self.offscreen_texture = self.ctx.texture(
            (self.wnd.buffer_width, self.wnd.buffer_height), 4)
        self.offscreen_depth = self.ctx.depth_texture(
            (self.wnd.buffer_width, self.wnd.buffer_height))
        self.offscreen = self.ctx.framebuffer(
            color_attachments=[self.offscreen_texture],
            depth_attachment=self.offscreen_depth,
        )
        bd = 1
        self.blur_h_texture = self.ctx.texture(
            (self.wnd.buffer_width // bd, self.wnd.buffer_height // bd), 4)
        self.blur_h_texture.repeat_x = False
        self.blur_h_texture.repeat_y = False
        self.blur_h = self.ctx.framebuffer(
            color_attachments=[self.blur_h_texture])
        self.blur_v_texture = self.ctx.texture(
            (self.wnd.buffer_width // bd, self.wnd.buffer_height // bd), 4)
        self.blur_v_texture.repeat_x = False
        self.blur_v_texture.repeat_y = False
        self.blur_v = self.ctx.framebuffer(
            color_attachments=[self.blur_v_texture])

        self.music_player = Player()
        self.music_source = StaticSource(
            load(RESOURCE_DIR / 'megalovania_remix/song.wav'))
        self.music_player.queue(self.music_source)
        self.music_player.play()
        # self.music_player.seek(60.0 * 4 + 50)
        self.music_player.volume = 1.0
示例#21
0
 def __init__(self, old: BackgroundMusic):
     """Get the music and position from the old player."""
     super().__init__()
     self.volume = old.volume
     self.queue(load(f'{ASSETS}audio/{old.track}.wav'))
     self.seek(old.time)
     self.play()
     self.loop = True
     pyglet.clock.schedule_once(self.fade_out, 0.1)
示例#22
0
 def load_file(self, name, ext, path):
     if ext in self.image_filetypes:
         self.image_dict[name + ext] = image.load(os.path.join(path, 
             '%s%s' % (name, ext))).get_texture()
         print "Image '%s' loaded!" % (name + ext)
     if ext in self.sound_filetypes:
         self.sound_dict[name + ext] = media.load(path + os.sep + name + ext,
                                                  streaming = False)
         print "Sound '%s' loaded!" % (name + ext)
示例#23
0
def main():
    director.init(**window)
    main_scene = Scene(StartLayer())

    player = Player()
    player.queue(load("resources/audios/cave.wav"))
    player.eos_action = player.EOS_LOOP
    player.play()

    director.run(main_scene)
def main():
    director.init(**window)
    main_scene = Scene(StartLayer())

    player = Player()
    player.queue(load("resources/audios/cave.wav"))
    player.eos_action = player.EOS_LOOP
    player.play()

    director.run(main_scene)
 def play_sound_once(self,soundfile,volume):
     if self.config.sound_switch>0:
         play_sound = Player()
         play_sound_source = load(soundfile)
         play_sound_group = SourceGroup(play_sound_source.audio_format, None)
         play_sound_group.loop = False
         play_sound_group.queue(play_sound_source)
         play_sound.queue(play_sound_group)
         play_sound.volume=float(volume) * self.config.sound_switch
         play_sound.play()
示例#26
0
def load_song(path):
    """Load a music stream from the music directory.

    :Parameters:
        `path` : str
            The relative path from the music directory to the file.

    """
    song_path = os.path.join(DATA_DIR, "music", path)
    return media.load(song_path)
示例#27
0
 def load_file(self, name, ext, path):
     if ext in self.image_filetypes:
         self.image_dict[name + ext] = image.load(
             os.path.join(path, '%s%s' % (name, ext))).get_texture()
         print "Image '%s' loaded!" % (name + ext)
     if ext in self.sound_filetypes:
         self.sound_dict[name + ext] = media.load(path + os.sep + name +
                                                  ext,
                                                  streaming=False)
         print "Sound '%s' loaded!" % (name + ext)
示例#28
0
 def move_bullets(self):
     """
     Moves the bullets for one frame.
     :return: None
     """
     for bullet in self.bullets:
         if self.current_time - bullet.creation_time >= TIME_UNTIL_BULLETS_ARE_DELETED:
             self.bullets.remove(bullet)
         bullet.move(self.current_time - self.last_time)
         bullet.set_hit_box()
         if not bullet.team and bullet.collision_test(self.player):
             self.music_player.pause()
             media.load("player_death.wav").play()
             self.playing = False
         for enemy in self.enemies:
             if bullet.team and bullet.collision_test(enemy):
                 self.enemies.remove(enemy)
                 self.enemies_killed += 1
                 media.load("enemy_death.wav").play()
示例#29
0
def load_sound(path):
    """Load a static sound source from the sounds directory.

    :Parameters:
        `path` : str
            The relative path from the sounds directory to the file.

    """
    sound_path = os.path.join(DATA_DIR, "sounds", path)
    return media.load(sound_path, streaming=False)
示例#30
0
文件: data.py 项目: jseutter/pyweek10
def load_sound(path):
    """Load a static sound source from the sounds directory.

    :Parameters:
        `path` : str
            The relative path from the sounds directory to the file.

    """
    sound_path = os.path.join(DATA_DIR, "sounds", path)
    return media.load(sound_path, streaming=False)
示例#31
0
文件: data.py 项目: jseutter/pyweek10
def load_song(path):
    """Load a music stream from the music directory.

    :Parameters:
        `path` : str
            The relative path from the music directory to the file.

    """
    song_path = os.path.join(DATA_DIR, "music", path)
    return media.load(song_path)
示例#32
0
文件: movie.py 项目: bitcraft/pyglet
    def __init__(self, parent, file=None, source=None, playing=False,
                 x=0, y=0, z=0, width=None, height=None, scale=True, **kw):
        self.parent = parent
        self.scale = scale

        if file is not None:
            source = self.source = media.load(file, streaming=True)
        else:
            assert source is not None, 'one of file or source is required'

        self.player = media.Player()
        self.player.eos_action = self.player.EOS_PAUSE
        self.player.on_eos = self.on_eos

        # poke at the video format
        if not source.video_format:
            raise ValueError("Movie file doesn't contain video")
        video_format = source.video_format
        if width is None:
            width = video_format.width
            if video_format.sample_aspect > 1:
                width *= video_format.sample_aspect
        if height is None:
            height = video_format.height
            if video_format.sample_aspect < 1:
                height /= video_format.sample_aspect

        super().__init__(parent, x, y, z, width, height, **kw)

        # control frame top-level
        c = self.control = Frame(self, bgcolor=(1, 1, 1, .5),
                                 is_visible=False, width='100%', height=64)

        # controls underlay
        f = Frame(c, is_transparent=True, width='100%', height='100%')
        f.layout = layouts.Horizontal(f, valign='center', halign='center',
                                      padding=10)
        c.play = Image(f, data.load_gui_image('media-play.png'),
                       classes=('-play-button',), is_visible=not playing)
        c.pause = Image(f, data.load_gui_image('media-pause.png'),
                        bgcolor=None, classes=('-pause-button',),
                        is_visible=playing)
        fi = Frame(f, is_transparent=True)
        c.range = Image(fi, data.load_gui_image('media-range.png'))
        im = data.load_gui_image('media-position.png')
        c.position = Image(fi, im, x=0, y=-2, classes=('-position',))
        c.time = Label(f, '00:00', font_size=20)
        c.anim = None

        # make sure we get at least one frame to display
        self.player.queue(source)
        clock.schedule(self.update)
        self.playing = False
        if playing:
            self.play()
def check_time():
    ctime = datetime.now().time().strftime("%I:%M:%S")
    if ctime[3:] == "00:00":
        src = "/home/pi/Desktop/chimes/chime.wav"
        chime = pg.load(src, streaming=False)
        player = pg.Player()
        player.volume = 0.5
        for h in range(int(ctime[:2])):
            player.queue(chime)
        player.play()
    threading.Timer(1, check_time).start()  #runs check_time every 1 sec
示例#34
0
 def switch_track(self, new: str):
     """Switch to a new track."""
     if self._source:
         FadeOut(self)
     self.track = new
     had_source = bool(self._source)
     self.queue(load(f'{ASSETS}audio/{new}.wav'))
     if had_source:
         self.next_source()
     self.volume = 0
     pyglet.clock.schedule_once(self.fade_in, 0.1)
示例#35
0
def is_audio_file(filename, media_file = None):
    if not media_file:
        try:
            media_file = media.load(filename)
        except:
            return False

    if media_file.video_format:
        return False

    return (media_file.audio_format is not None)
示例#36
0
def main():
    fname='/home/evan/Desktop/openJarvis/openJarvis/speech/tdfw.mp3'
    src=media.load(fname)
    player=media.Player()
    player.queue(src)
    player.volume=1.0
    player.play()
    try:
        pyglet.app.run()
    except KeyboardInterrupt:
        player.next()
示例#37
0
def main():
    fname = '/home/evan/Desktop/openJarvis/openJarvis/speech/tdfw.mp3'
    src = media.load(fname)
    player = media.Player()
    player.queue(src)
    player.volume = 1.0
    player.play()
    try:
        pyglet.app.run()
    except KeyboardInterrupt:
        player.next()
示例#38
0
 def open_playlist(self, player, time_slider, display):
     folder = fd.askdirectory()
     for root, dirs, files in os.walk(folder):
         for filename in files:
             path = os.path.join(root, str(filename))
             if not os.path.exists(path):
                 print('File not found; program terminated')
                 sys.exit()
             src = media.load(path, streaming=True)
             player.player.queue(src)
     player.play()
     self.change_display(display, player)
示例#39
0
 def enemy_move(self):
     """
     Moves the enemies for one frame.
     :return: None
     """
     if self.current_time - self.last_enemy_spawn_time >= TIME_BETWEEN_ENEMY_SPAWNS\
             and len(self.enemies) <= MAX_ENEMIES:
         self.last_enemy_spawn_time = self.current_time
         self.enemies.append(
             create_enemy_semi_random_position(self.player.x_pos,
                                               self.player.y_pos))
     for enemy in self.enemies:
         enemy.chase_player(self.player.x_pos, self.player.y_pos)
         enemy.drag(ENEMY_DRAG)
         enemy.rotate_enemy()
         enemy.move(self.current_time - self.last_time)
         enemy.set_hit_box()
         if self.current_time - enemy.last_shot_time >= DELAY_BETWEEN_ENEMY_SHOTS:
             enemy.last_shot_time = self.current_time
             self.enemy_shoot(enemy)
             media.load("bullet.wav").play()
示例#40
0
def playSounds(instrument, notes):
	sound = media.load(instrument, streaming=False)
	pitch = 0
	for c in notes:
		if c.isdigit():
			player = media.Player()
			player.queue(sound)
			player.pitch = (2.0**(float(c)/12))
			#player.pitch = int(c)
			#print player.pitch
			player.play()
			sleep(2)
示例#41
0
 def open_files(self, player, time_slider, display):
     files = fd.askopenfilenames()
     # check file legitimacy
     for filename in files:
         path = str(filename)
         if not os.path.exists(path):
             print('File not found; program terminated')
             sys.exit()
         src = media.load(path, streaming=True)
         player.player.queue(src)
     player.play()
     self.change_display(display, player)
示例#42
0
 def player_move(self):
     """
     Moves the player for one frame.
     :return: None
     """
     if self.turn_counter_clockwise:
         self.player.angle += PLAYER_TURN_ANGLE
         self.player.rotate_player()
     if self.turn_clockwise:
         self.player.angle -= PLAYER_TURN_ANGLE
         self.player.rotate_player()
     if self.accelerate:
         self.player.speed_up()
     if self.shoot and self.current_time - self.last_player_shot_time >= DELAY_BETWEEN_PLAYER_SHOTS:
         self.last_player_shot_time = self.current_time
         self.player_shoot()
         media.load("bullet.wav").play()
     self.player.drag(PLAYER_DRAG)
     self.player.move(self.current_time - self.last_time)
     self.player.gravity()
     self.player.set_hit_box()
示例#43
0
 def playAudioFile(self, filename, stream=False):
     try:
         volume = float(self.volume) / 100.0
         if self.player:
             src = media.load(filename, streaming=stream)
             self.player.queue(src)
             self.player.volume = volume
             self.player.play()
         elif self.isDarwin:
             subprocess.call(["afplay -v {0} {1}".format(volume, filename)], shell=True)
     except Exception as e:
         logging.error("SoundThread.playAudioFile exception: %s", e)
示例#44
0
 def playAudioFile(self, filename, stream=False):
     try:
         volume = float(self.volume) / 100.0
         if self.player:
             src = media.load(filename, streaming=stream)
             self.player.queue(src)
             self.player.volume = volume
             self.player.play()
         elif self.isDarwin:
             subprocess.call(["afplay -v {0} {1}".format(volume, filename)], shell=True)
     except Exception as e:
         logging.error("SoundThread.playAudioFile exception: %s", e)
示例#45
0
文件: music.py 项目: bitcraft/pyglet
    def __init__(self, parent, file=None, source=None, title=None,
                 playing=False, bgcolor=(1, 1, 1, 1), color=(0, 0, 0, 1),
                 font_size=20, **kw):
        """Pass in a filename as "file" or a pyglet Source as "source".
        """
        self.parent = parent

        if file is not None:
            source = media.load(file, streaming=True)
        else:
            assert source is not None, 'one of file or source is required'

        self.player = media.Player()

        # poke at the audio format
        if not source.audio_format:
            raise ValueError("File doesn't contain audio")

        super().__init__(parent, bgcolor=bgcolor, **kw)

        # lay it out

        # control frame top-level
        c = self.control = Frame(self, width='100%', height=64)

        ft = Frame(c, is_transparent=True, width='100%', height='100%')
        ft.layout = layouts.Vertical(ft)
        Label(ft, title or 'unknown', color=color, bgcolor=bgcolor,
              padding=2, font_size=font_size)

        # controls underlay
        f = Frame(ft, is_transparent=True, width='100%', height='100%')
        f.layout = layouts.Horizontal(f, valign='center', halign='center',
                                      padding=10)
        c.play = Image(f, data.load_gui_image('media-play.png'),
                       classes=('-play-button',), is_visible=not playing)
        c.pause = Image(f, data.load_gui_image('media-pause.png'),
                        bgcolor=None, classes=('-pause-button',),
                        is_visible=playing)
        fi = Frame(f, is_transparent=True)
        c.range = Image(fi, data.load_gui_image('media-range.png'))
        c.position = Image(fi, data.load_gui_image('media-position.png'),
                           y=-2, classes=('-position',))
        c.time = Label(f, '00:00', font_size=20)
        c.anim = None

        # make sure we get at least one frame to display
        self.player.queue(source)
        clock.schedule(self.update)
        self.playing = False
        if playing:
            self.play()
示例#46
0
    def __init__(self,
                 ec,
                 file_name,
                 pos=(0, 0),
                 units='norm',
                 scale=1.,
                 center=True,
                 visible=True):
        from pyglet.media import load, Player
        self._ec = ec
        # On Windows, the default is unaccelerated WMF, which is terribly slow.
        decoder = None
        if _new_pyglet():
            try:
                from pyglet.media.codecs.ffmpeg import FFmpegDecoder
                decoder = FFmpegDecoder()
            except Exception as exc:
                warnings.warn(
                    'FFmpeg decoder could not be instantiated, decoding '
                    f'performance could be compromised:\n{exc}')
        self._source = load(file_name, decoder=decoder)
        self._player = Player()
        with warnings.catch_warnings(record=True):  # deprecated eos_action
            self._player.queue(self._source)
        self._player._audio_player = None
        frame_rate = self.frame_rate
        if frame_rate is None:
            logger.warning('Frame rate could not be determined')
            frame_rate = 60.
        self._dt = 1. / frame_rate
        self._playing = False
        self._finished = False
        self._pos = pos
        self._units = units
        self._center = center
        self.set_scale(scale)  # also calls set_pos
        self._visible = visible
        self._eos_fun = self._eos_new if _new_pyglet() else self._eos_old

        self._program = _create_program(ec, tex_vert, tex_frag)
        gl.glUseProgram(self._program)
        self._buffers = dict()
        for key in ('position', 'texcoord'):
            self._buffers[key] = gl.GLuint(0)
            gl.glGenBuffers(1, pointer(self._buffers[key]))
        w, h = self.source_width, self.source_height
        tex = np.array([(0, h), (w, h), (w, 0), (0, 0)], np.float32)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._buffers['texcoord'])
        gl.glBufferData(gl.GL_ARRAY_BUFFER, tex.nbytes, tex.tobytes(),
                        gl.GL_DYNAMIC_DRAW)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
        gl.glUseProgram(0)
示例#47
0
		def playAudioFile(self, filename, stream=False):
			try:
				volume = float(SoundManager.soundVolume) / 100.0
				if gPygletAvailable:
					src = media.load(filename, streaming=stream)
					player = media.Player()
					player.queue(src)
					player.volume = volume
					player.play()
				elif self.isDarwin:
					subprocess.call(["afplay -v {0} {1}".format(volume, filename)], shell=True)
			except Exception as e:
				print "SoundThread.playAudioFile exception: %s" % str(e)
示例#48
0
    def __init__(self, parent, file=None, source=None, title=None,
            playing=False, bgcolor=(1, 1, 1, 1), color=(0, 0, 0, 1),
            font_size=20, **kw):
        '''Pass in a filename as "file" or a pyglet Source as "source".
        '''
        self.parent = parent

        if file is not None:
            source = media.load(file, streaming=True)
        else:
            assert source is not None, 'one of file or source is required'

        self.player = media.Player()

        # poke at the audio format
        if not source.audio_format:
            raise ValueError("File doesn't contain audio")

        super(Music, self).__init__(parent, bgcolor=bgcolor, **kw)

        # lay it out

        # control frame top-level
        c = self.control = Frame(self, width='100%', height=64)

        ft = Frame(c, is_transparent=True, width='100%', height='100%')
        ft.layout = layouts.Vertical(ft)
        Label(ft, title or 'unknown', color=color, bgcolor=bgcolor,
            padding=2, font_size=font_size)

        # controls underlay
        f = Frame(ft, is_transparent=True, width='100%', height='100%')
        f.layout = layouts.Horizontal(f, valign='center', halign='center',
            padding=10)
        c.play = Image(f, data.load_gui_image('media-play.png'),
            classes=('-play-button',), is_visible=not playing)
        c.pause = Image(f, data.load_gui_image('media-pause.png'),
            bgcolor=None, classes=('-pause-button',), is_visible=playing)
        fi = Frame(f, is_transparent=True)
        c.range = Image(fi, data.load_gui_image('media-range.png'))
        c.position = Image(fi, data.load_gui_image('media-position.png'),
            y=-2, classes=('-position',))
        c.time = Label(f, '00:00', font_size=20)
        c.anim = None

        # make sure we get at least one frame to display
        self.player.queue(source)
        clock.schedule(self.update)
        self.playing = False
        if playing:
            self.play()
示例#49
0
文件: sound.py 项目: adrallor/Gjam
    def __init__(self, file_name: Union[str, Path], streaming: bool = False):
        self.file_name: str = ""

        file_name = resolve_resource_path(file_name)

        if not Path(file_name).is_file():
            raise FileNotFoundError(
                f"The sound file '{file_name}' is not a file or can't be read."
            )
        self.file_name = str(file_name)

        self.source: Union[media.StaticSource, media.StreamingSource] = media.load(self.file_name, streaming=streaming)

        self.min_distance = 100000000 #setting the players to this allows for 2D panning with 3D audio
示例#50
0
def get_metadata(filename, media_file = None):
    from metadata import Metadata
    if not media_file:
        media_file = media.load(filename)

    if not is_audio_file('', media_file):
        return None

    md = media_file.file_info

    return Metadata(title=md.title, artist=md.author, 
            album=md.album, year=md.year, 
            trackno=md.track, genre=md.genre,
            duration=md.duration
            )
示例#51
0
    def __init__(self, filename):

        self.issbfmf = False
        self.source = media.load(filename)
        self.ZERO = 0.00001
        self.source._seek(self.ZERO)
        self.start_time = self.source.get_next_video_timestamp()

        # estimate properties of the video that would be nice
        # to be able to read in -- i have no idea how accurate
        # these estimates are
        self.duration_seconds = self.source.duration
        self._estimate_fps()
        self.frame_delay_us = 1e6 / self.fps
        self._estimate_keyframe_period()
        self.n_frames = int(num.floor(self.duration_seconds * self.fps))
        print "n_frames estimated to be %d" % self.n_frames

        # added to help masquerade as FMF file:
        self.filename = filename

        # read in the width and height of each frame
        self.width = self.source.video_format.width
        self.height = self.source.video_format.height

        self.MAXBUFFERSIZE = num.round(200 * 1000 * 1000 / self.width / self.height)
        self.buffersize = min(self.MAXBUFFERSIZE, self.keyframe_period)

        # compute the bits per pixel
        self.source._seek(self.ZERO)
        im = self.source.get_next_video_frame()
        im = num.fromstring(im.data, num.uint8)
        self.color_depth = len(im) / self.width / self.height
        if self.color_depth != 1 and self.color_depth != 3:
            raise ValueError(
                "color_depth = %d, only know how to deal with color_depth = 1 or colr_depth = 3" % self.color_depth
            )
        self.bits_per_pixel = self.color_depth * 8

        # allocate the buffer
        self.buffer = num.zeros((self.height, self.width, self.buffersize), dtype=num.uint8)
        self.bufferts = num.zeros(self.buffersize)
        # put the first frame in it
        self.source._seek(self.ZERO)
        self.currframe = 0
        (frame, ts) = self.get_next_frame_and_reset_buffer()

        self._all_timestamps = None
示例#52
0
def load_source(name, path):
    """
    Registers a new sound with the name "name" from the source specified by "path".
    Once a source has been loaded, you can play it by calling AudioPlayer.play("name")
    """
    global _sources

    # Use pyglet.media to load the Source
    source = media.load(path, None, False)

    if source is not None:
        # Convert our source to a static source to allow for
        # overlapping playback
        static_source = media.StaticSource(source)
        _sources[name] = static_source
    else:
        print "Unable to load " + path + ", check path."
示例#53
0
def play(message):
    argname = message.content[6:]
    songname = ''
    if argname.len() < 3:
        client.send_message(message.channel, '```Songname too short```')
        return
    try:
        files = [f for f in os.listdir('music') if os.path.isfile('music/' + f)]
        for f in files:
            if f.startswith(argname):
                songname = f
                break
        song = media.load('music/' + songname, streaming=False)
        player.queue(song)
        player.play()
    except FileNotFoundError:
        client.send_message(message.channel, '```No such file or directory```')
示例#54
0
文件: _visual.py 项目: ilogue/expyfun
 def __init__(self, ec, file_name, pos=(0, 0), units='norm', scale=1.,
              center=True):
     from pyglet.media import load, Player
     self._ec = ec
     self._source = load(file_name)
     self._player = Player()
     self._player.queue(self._source)
     self._player._audio_player = None
     self._dt = 1. / self.frame_rate
     self._texture = None
     self._playing = False
     self._finished = False
     self._pos = pos
     self._units = units
     self._center = center
     self._scale = scale
     self.set_scale(self._scale)  # also calls set_pos
示例#55
0
def set_background_music(path):
    """
    Sets the background music to the file specified by "path"
    Once background music has been set, you can play it by calling AudioPlayer.play_background_music()
    """

    # Background music is handled a bit differently than other sounds
    # Since it must stream and loop, we cannot use StaticSource.play() to create a ManagedPlayer
    # Instead, load create a Source object from file, and a Player() from this Source
    # This will be our background music Player
    global _bg_music_source
    global _bg_music_player

    _bg_music_source = media.load(path, None, False)
    _bg_music_player = media.Player()
    _bg_music_player.eos_action = media.Player.EOS_LOOP
    _bg_music_player.queue(_bg_music_source)
    _bg_music_player.pause()
 def play_song(self, *args, **kwargs):
     if self.path.get():
         try:
             self.reset_player()
             try:
                 src=media.load(self.path.get())
                 self.player.queue(src)
                 self.play()
                 
                 self.songduration.set(self.duration_())   # Updating duration Time
                 return 
             except Exception as e:
                 print ("[+] Something wrong when playing song",e)
                 return 
         except Exception as e:
             print (' [+] Please Check Your File Path', self.path.get())
             print (' [+] Error: Problem On Playing \n ',e)
             return 
     else:
         print (' [+] Please Check Your File Path', self.path.get())
     return
示例#57
0
 def __init__(self, ec, file_name, pos=(0, 0), units='norm', scale=1.,
              center=True, visible=True):
     from pyglet.media import load, Player
     self._ec = ec
     self._source = load(file_name)
     self._player = Player()
     self._player.queue(self._source)
     self._player._audio_player = None
     frame_rate = self.frame_rate
     if frame_rate is None:
         logger.warning('Frame rate could not be determined')
         frame_rate = 60.
     self._dt = 1. / frame_rate
     self._texture = None
     self._playing = False
     self._finished = False
     self._pos = pos
     self._units = units
     self._center = center
     self.set_scale(scale)  # also calls set_pos
     self._visible = visible
示例#58
0
    def open(self, filename):
        song = media.load(filename)

        if not is_audio_file('', song):
            raise MediaError('File "%s" is not an audio or audio only file' % filename)

        playing = False
        if self._player and self._player.playing:
            playing = True

        self.stop()

        self._lock()
        try:
            self._player = None
        finally:
            self._unlock()

        self._filename = filename
        self._song = song
        self._metadata = get_metadata('', song)

        if playing:
            self.play()
示例#59
0
 def __init__(self, filename):
     player.queue(load(filename))
     self.is_paused = False
     self.is_stopped = False