def __init__(self, settings): self.speed = int(settings['-r']) if '-r' in settings else 20 self.scale = float(settings['-s']) if '-s' in settings else 1.0 self.screen = curses.initscr() self.START_INTENSITY = int(settings['-i']) if '-i' in settings else self.MAX_INTENSITY self.START_OFFSET = int(settings['-w']) if '-w' in settings else 0 self.START_HEIGHT = int(settings['-h']) if '-h' in settings else 0 self.screen.clear() self.screen.nodelay(1) curses.curs_set(0) curses.start_color() curses.use_default_colors() for i in range(0, curses.COLORS): curses.init_pair(i, i, -1) def color(r, g, b): return (16+r//48*36+g//48*6+b//48) self.heat = [color(16 * i,0,0) for i in range(0,16)] + [color(255,16 * i,0) for i in range(0,16)] self.particles = [ord(i) for i in (' ', '.', '*', '#', '@')] assert(len(self.particles) == self.NUM_PARTICLES) self.resize() self.volume = 1.0 if pygame_available: mixer.init() music.load('fire.wav') music.play(-1) elif pyaudio_available: self.loop = True self.lock = threading.Lock() t = threading.Thread(target=self.play_fire) t.start()
def _load_assets(self): music.load("assets/music.ogg") self.sounds = { "bitten": Sound("assets/bitten.ogg"), "click": Sound("assets/click.ogg"), "eat": Sound("assets/eat.ogg"), }
def play_song(filename): global current_song global MUSIC_PATH if filename != current_song: music.load(MUSIC_PATH + filename) music.play(-1) current_song = filename
def _load_sounds(self): """Load sounds to be played.""" self.sound_files = dict() # Get address files for key in self.sound_type.keys(): limit = len(self.sound_type[key]) - 1 index = random.randint(0, limit) self.sound_files[key] = self.sound_type[key][index] self.opened_sounds, self.channels = dict(), dict() i = 0 # For shots, exploded_alien, lost_ship, new_level for key in list(self.sound_type.keys())[2:]: self.opened_sounds[key] = Sound(self.sound_files[key]) self.channels[key] = pygame.mixer.Channel(i) i += 1 music.load(self.sound_files['menu']) music.play(loops=-1) self.channels['shots'].set_volume(0.1) self.channels['exploded_alien'].set_volume(0.2) self.channels['lost_ship'].set_volume(1.0) self.channels['new_level'].set_volume(0.6) self.channels['game_over'].set_volume(1.0)
def update(self, time): print ('update', self._filename, self._playing, time, self._start_time, self._end_time) if time < self._start_time: pass elif self._playing == 'no': try: music.stop() music.load(self._filename) music.set_volume(0.01) # 0.0 stops pygame.mixer.music. # Workaround for a pygame/libsdl mixer bug. #music.play(0, self._start) music.play(0, 0) self._playing = 'yes' except: # Filename not found? Song is too short? SMPEG blows? music.stop() self._playing = 'no' elif time < self._start_time + 1000: # mixer.music can't fade in music.set_volume((time - self._start_time) / 1000.0) elif (time > self._end_time - 1000) and self._playing == 'yes': self._playing = 'fadeout' music.fadeout(1000) elif time > self._end_time: music.stop() dt = pygame.time.get_ticks() + 1000 - self._start_time self._end_time = dt + self._end_time self._start_time = dt + self._start_time self._playing = 'no'
def level_menu(g, keys): if keys[K_r]: g.restart_game() g.mode = F_GAME if (g.opt_music == True): music.rewind() music.play(-1) if keys[K_q]: g.mode = F_MAIN_MENU if (g.opt_music == True): music.load(os.path.join(media_folder, 'main_menu_music.wav')) music.play(-1) g.menu_timer -= g.dt if g.menu_timer <= 0: if keys[K_RETURN]: g.level_menu.function[g.level_menu.text.new_pos - g.level_menu.text.offset_title_select](g) g.menu_timer = MENU_INPUT_DELAY if keys[K_UP]: if (g.opt_sfx is True): g.sound_move_cursor.play() g.level_menu.text.move_up() g.menu_timer = MENU_INPUT_DELAY if keys[K_DOWN]: if (g.opt_sfx is True): g.sound_move_cursor.play() g.level_menu.text.move_down() g.menu_timer = MENU_INPUT_DELAY
def set_music_enabled(state: bool): """ Enables or disables music. .. Note:: To work around a bug in the pygame music system, disabling music will cause the currently playing music to be started again from the beginning when music is re-enabled. Args: state: The new state """ global music_enabled if music_enabled != state: music_enabled = state if state: if current_music: # After stopping and restarting currently loaded music, # fadeout no longer works. # print "albow.music: reloading", repr(current_music) ### music.load(current_music) music.play() else: MusicUtilities.jog_music() else: music.stop()
def update(self, time): print('update', self._filename, self._playing, time, self._start_time, self._end_time) if time < self._start_time: pass elif self._playing == 'no': try: music.stop() music.load(self._filename) music.set_volume(0.01) # 0.0 stops pygame.mixer.music. # Workaround for a pygame/libsdl mixer bug. #music.play(0, self._start) music.play(0, 0) self._playing = 'yes' except: # Filename not found? Song is too short? SMPEG blows? music.stop() self._playing = 'no' elif time < self._start_time + 1000: # mixer.music can't fade in music.set_volume((time - self._start_time) / 1000.0) elif (time > self._end_time - 1000) and self._playing == 'yes': self._playing = 'fadeout' music.fadeout(1000) elif time > self._end_time: music.stop() dt = pygame.time.get_ticks() + 1000 - self._start_time self._end_time = dt + self._end_time self._start_time = dt + self._start_time self._playing = 'no'
def __init__(self, settings): self.speed = int(settings['-r']) if '-r' in settings else 20 self.scale = float(settings['-s']) if '-s' in settings else 1.0 self.screen = curses.initscr() self.height, self.width = self.screen.getmaxyx()#[:2] self.START_INTENSITY = int(settings['-i']) if '-i' in settings else self.MAX_INTENSITY self.START_OFFSET = int(settings['-w']) if '-w' in settings else 0 self.START_HEIGHT = int(settings['-h']) if '-h' in settings else 0 self.screen.clear() self.screen.nodelay(1) mixer.init() music.load('../fire.wav') music.play(-1) self.volume = 1.0 curses.curs_set(0) curses.start_color() curses.use_default_colors() for i in range(0, curses.COLORS): curses.init_pair(i, i, -1) def color(r, g, b): return (196+r//48*6+g//48*36+b//48) self.heat = [color(16 * i,0,0) for i in range(0,16)] #+ [color(255,16 * i,0) for i in range(0,16)] self.particles = [ord(i) for i in (' ', '.', '*', '#', '@')] assert(len(self.particles) == self.NUM_PARTICLES) self.resize()
def __init__(self): self._playing = False self._filename = None self._end_time = self._start_time = 0 if not mainconfig["previewmusic"]: music.load(os.path.join(sound_path, "menu.ogg")) music.play(4, 0.0)
def __init__(self, resourcemgr, team, level): super(InGame, self).__init__(resourcemgr) self.tilemgr = TileManager(resourcemgr, level) self.unitmgr = UnitManager(resourcemgr, STATES.INGAME, team, level) self.lw = self.tilemgr.lw self.lh = self.tilemgr.lh self.team = team # self.bar = Bar(config) music.load(os.path.join(resourcemgr.main_path, 'sound/yyz.ogg')) self.camera = Camera(0, 0, self.lw, self.lh, resourcemgr) font = SysFont(FONTS, int(48 * resourcemgr.scale), True) self.win_msg = font.render('YOU WINNN!!! GGGG GGGGGGGGGGGGGGG', 1, WHITE) self.win_msg_rect = self.win_msg.get_rect( centerx=self.camera.rect.w / 2, centery=self.camera.rect.h / 4) self.lose_msg = font.render('You lost. What the f**k, man?', 1, BLACK) self.lose_msg_rect = self.win_msg.get_rect( centerx=self.camera.rect.w / 2, centery=self.camera.rect.h / 4) self.mouse_rect = Rect(0, 0, 0, 0) self.x_first = 0 self.y_first = 0 self.won = False self.lost = False self.gg = load_sound(resourcemgr.main_path, 'gg.ogg') self.lose = load_sound(resourcemgr.main_path, 'lose.ogg')
def init(fname): mixer.init(22050, -16, 2, 1024) music.load(fname) music.rewind() music.play() music.pause() music.rewind()
def run(self): while True: target, nontarget, tname, ntname, evalue, word, t, count, allele = self.blastqueue.get() threadlock.acquire() if os.path.getsize(target) != 0: # BLASTn parameters blastn = NcbiblastnCommandline(query=target, db=nontarget, evalue=evalue, outfmt=6, perc_identity=85, word_size=word, # ungapped=True, # penalty=-20, # reward=1, ) stdout, stderr = blastn() sys.stdout.write('[%s] [%s/%s] ' % (time.strftime("%H:%M:%S"), count, t)) if not stdout: print colored("%s has no significant similarity to \"%s\"(%i) with an elimination E-value: %g" % (tname, ntname, allele, evalue), 'red') else: music.load('/run/media/blais/blastdrive/coin.wav') music.play() print colored("Now eliminating %s sequences with significant similarity to \"%s\"(%i) with an " "elimination E-value: %g" % (tname, ntname, allele, evalue), 'blue', attrs=['blink']) blastparse(stdout, target, tname, ntname) else: global result result = None threadlock.release() self.blastqueue.task_done()
def play_song(filename, volume=0.75): global current_song global MUSIC_PATH if filename != current_song: music.load(MUSIC_PATH + filename) music.set_volume(volume) music.play(-1) current_song = filename
def play_bgm(self, path, stream=False): self.stop_current_channel() if stream: music.load(path) music.play(-1) else: self.current_channel = Sound(path).play(-1) self.set_volume()
def __play(self, music_file): # self.playing_flag = True # while self.playing_flag: # if not music.get_busy(): # music.load(music_file) # music.play(-1) music.load(music_file) music.play(1)
def playOffline(matrix): mp3 = ['small.mp3', 'hihat.mp3', 'down.mp3', 'snare.mp3'] now = matrix.maps[matrix.now_layer] # print('=====', self.maps[self.now_layer], '=====') # print('-----', now.index('1'), '-----') init() music.load('music/' + mp3[now.index('1')]) music.play()
def start(self): #line music.load(os.path.join("games", "lineMathCombo", "finalSound.wav")) music.play() #maths self.answer = self.addans self.winner = False self.losing = 0
def but_pushD(): global cycle if button[5].is_pressed: a = 3 else: a = cycle music.load(buttonsound[a][3]) music.play()
def play_music(self): if music_player.get_busy(): return music_player.load(MUSIC[self.current_track]) music_player.play(1) self.current_track += 1 if self.current_track == len(MUSIC): self.current_track = 0
def CreditsMenu(): music.load(join(f_music, 'Credits_Music.ogg')) music.set_volume(0.5) music.play(loops=-1) check_credits_menu = True coin_animation = 1 coin_animation_control = 0 num_image = 1 y_mov = 0 background_animation_control = 0 button_back = Rect(400, 690, 192, 42) button_cat_sound = Rect(850, 500, 100, 100) while check_credits_menu: CLOCK.tick(60) mouse_pos = mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == MOUSEBUTTONDOWN and event.button == 1: if button_back.collidepoint(mouse.get_pos()): sfxButtonClick.play() check_credits_menu = False if button_cat_sound.collidepoint(mouse.get_pos()): sfxCat.play() ButtonsPrint(button_cat_sound, ':3', menuFont) SCREEN.blit(scale(load(join(f_backgrounds, f'Credits_{num_image}.png')) .convert_alpha(), (1040, 701)), (0, 80)) y_move = y_mov % imgCredits.get_rect().height SCREEN.blit(imgCredits, (0, (y_move - imgCredits.get_rect().height))) if y_move < Height: SCREEN.blit(imgCredits, (0, y_move)) SCREEN.blit(scale(load(join(f_backgrounds, f'CreditsT_{num_image}.png')) .convert_alpha(), (1040, 701)), (0, 80)) ButtonsPrint(button_back, 'BACK', menuFont) SCREEN.blit(imgCursor, (mouse_pos[0], mouse_pos[1])) SCREEN.blit(bgArcadeMenu, (0, 0)) SCREEN.blit(scale(load(join(f_coin, f'Coin_{coin_animation}.png')) .convert_alpha(), (220, 150)), (370, 855)) y_mov -= 0.75 coin_animation_control += 0.5 background_animation_control += 1 if background_animation_control % 8 == 0: num_image += 1 if num_image == 9: num_image = 1 if coin_animation_control % 6 == 0: coin_animation += 1 if coin_animation > 6: coin_animation = 1 coin_animation_control = 0 display.update() music.stop()
def __init__(self): pre_init(22050, -16, 2, 1024) init() quit() init(22050, -16, 2, 1024) music.load(cfg.MUSIC_FILE) self.eatSfx = Sound(cfg.EAT_SFX_FILE) self.collideSfx = Sound(cfg.COLLIDE_SFX_FILE) self.winSfx = Sound(cfg.WIN_SFX_FILE)
def begin(self): music.load('hamster_dance.wav') music.play(-1) box = self.root.ids.box box.clear_widgets() label = ColourLabel() box.add_widget(label) Clock.schedule_once(self.flash, 0) self.interval_flash = Clock.schedule_interval(self.flash, 0.45)
def but_pushA(): global cycle if button[5].is_pressed: a = 3 else: a = cycle print(a) music.load(buttonsound[a][0]) music.play()
def __init__(self, songs, courses, screen, game): InterfaceWindow.__init__(self, screen, "courseselect-bg.png") recordkeys = dict([(k.info["recordkey"], k) for k in songs]) self._courses = [CourseDisplay(c, recordkeys, game) for c in courses] self._all_courses = self._courses self._index = 0 self._clock = pygame.time.Clock() self._game = game self._config = dict(game_config) self._configs = [] self._list = ListBox(FontTheme.Crs_list, [255, 255, 255], 32, 10, 256, [373, 150]) if mainconfig["folders"]: self._create_folders() self._create_folder_list() else: self._folders = None self._base_text = _("All Courses") self._courses.sort(SORTS[SORT_NAMES[mainconfig["sortmode"] % NUM_SORTS]]) self._list.set_items([s.name for s in self._courses]) self._course = self._courses[self._index] self._course.render() players = games.GAMES[game].players for i in range(players): self._configs.append(dict(player_config)) ActiveIndicator([368, 306], height=32, width=266).add(self._sprites) HelpText(CS_HELP, [255, 255, 255], [0, 0, 0], FontTheme.help, [186, 20]).add(self._sprites) self._list_gfx = ScrollingImage(self._course.image, [15, 80], 390) self._coursetitle = TextDisplay('Crs_course_name', [345, 28], [20, 56]) self._title = TextDisplay('Crs_course_list_head', [240, 28], [377, 27]) self._banner = ImageDisplay(self._course.banner, [373, 56]) self._sprites.add([ self._list, self._list_gfx, self._title, self._coursetitle, self._banner ]) self._screen.blit(self._bg, [0, 0]) pygame.display.update() self.loop() music.fadeout(500) pygame.time.wait(500) # FIXME Does this belong in the menu code? Probably. music.load(os.path.join(sound_path, "menu.ogg")) music.set_volume(1.0) music.play(4, 0.0) player_config.update(self._configs[0]) # Save p1's settings game_config.update(self._config) # save game settings
def play(self,filename,loops=-1,start=0.0): if not self.filename: self.stop() self.filename = filename try: music.load(filename) except: print "bad filename or i/o error on "+filename+"check file name and its status" self.channel = music.play(loops,start)
def next(): global index global playing displayH("next") mp3.load(l[index]) mp3.play() playing = True displayCL() sleep(1) displayH("play")
def previous(): global index global playing displayH("previous") mp3.load(l[index]) mp3.play() playing = True displayCL() sleep(1) displayH("play")
def __init__(self, event_handler) -> None: super(MenuScene, self).__init__(event_handler, MenuWorld(), Background('MENU.png')) self._menu = Menu(self) self._event_handler.subscribe_entity(self._menu) file_path = "songs/epicsaxguys.wav" file_wav = wave.open(file_path) frequency = file_wav.getframerate() mixer.init(frequency=frequency) music.load(file_path)
def on_click(self, pos): pos = (pos[0] - self.pos[0], pos[1] - self.pos[1]) if self.sprite_rect.h != 0 and self.sprite_rect.collidepoint(pos[0], pos[1]): global HIT self.status = HIT self.time = 0 self.sprite_rect.h, self.sprite_rect.y = 0, int(self.rect.centery) music.load("ow.mp3") music.play(0, 0) return 1 return 0
def __say(self, desire): """Given a string of text, speak it. Args: desire (str): Text to speak. """ tts = gTTS(desire, 'en-uk') tts.save('sounds/temp_voice.mp3') self.play_sound('temp_voice') # Load a different, constant sound to prevent IO errors music.load('sounds/akuwhat.mp3')
def play_next(): global AUDIO_LIBRARY global CURRENT_POS CURRENT_POS = (CURRENT_POS + 1) % len(AUDIO_LIBRARY) print("Now playing {} ({}) - audio file {} of {}.".format( _get_current_song(), str(timedelta(seconds=_get_length_of_mp3(_get_current_song()))), CURRENT_POS + 1, len(AUDIO_LIBRARY))) music.load(_get_current_song()) music.play()
def play_menu_music(self): """Проигрывание музыки во время нахождения в меню""" if self.sound: for sound in self.sounds.values(): sound: Sound sound.stop() music.unpause() music.unload() music.load('music/background.mp3') music.set_volume(1) music.play(-1)
def __init__(self): """ Args: - Action: Create a Song that can be played. """ name_song = choice(Music_Config['NAME_MUSIC'])+'_'+\ choice(Music_Config['NAME_GEN']) music.load(Directory['DIR_MUSIC'] + name_song + Music_Config['EXTENSION']) music.set_volume(Music_Config['VOLUME'] / 100)
def start_next_music(): """Start playing the next item from the current playlist immediately.""" #print "albow.music: start_next_music" ### global current_music, next_change_delay if music_enabled and current_playlist: next_music = current_playlist.next() if next_music: print "albow.music: loading", repr(next_music) ### music.load(next_music) music.play() next_change_delay = change_delay current_music = next_music
def playmusic(_file: str) -> None: """Play an MP3, WAV, or other audio file via Pygame3""" try: from pygame.mixer import init, music except ImportError: raise Exception(r'Pygame is not installed or found.') init() music.load(_file) music.play() while music.get_busy() is True: continue return None
def orchestrate(phonograph_name, once=False): if not SOUND_ON: return global MUSIC_PLAYING if MUSIC_PLAYING == phonograph_name: return path = data.filepath(os.path.join("numerical_phonographs", phonograph_name)) if MUSIC_PLAYING: music.fadeout(1000) music.load(path) music.play(0 if once else -1) MUSIC_PLAYING = phonograph_name
def __init__(self, songs, courses, screen, game): InterfaceWindow.__init__(self, screen, "courseselect-bg.png") recordkeys = dict([(k.info["recordkey"], k) for k in songs]) self._courses = [CourseDisplay(c, recordkeys, game) for c in courses] self._all_courses = self._courses self._index = 0 self._clock = pygame.time.Clock() self._game = game self._config = dict(game_config) self._configs = [] self._list = ListBox(FontTheme.Crs_list, [255, 255, 255], 32, 10, 256, [373, 150]) if len(self._courses) > 60 and mainconfig["folders"]: self._create_folders() self._create_folder_list() else: self._folders = None self._base_text = _("All Courses") self._courses.sort(SORTS[SORT_NAMES[mainconfig["sortmode"] % NUM_SORTS]]) self._list.set_items([s.name for s in self._courses]) self._course = self._courses[self._index] self._course.render() players = games.GAMES[game].players for i in range(players): self._configs.append(dict(player_config)) ActiveIndicator([368, 306], height = 32, width = 266).add(self._sprites) HelpText(CS_HELP, [255, 255, 255], [0, 0, 0], FontTheme.help, [186, 20]).add(self._sprites) self._list_gfx = ScrollingImage(self._course.image, [15, 80], 390) self._coursetitle = TextDisplay('Crs_course_name', [345, 28], [20, 56]) self._title = TextDisplay('Crs_course_list_head', [240, 28], [377, 27]) self._banner = ImageDisplay(self._course.banner, [373, 56]) self._sprites.add([self._list, self._list_gfx, self._title, self._coursetitle, self._banner]) self._screen.blit(self._bg, [0, 0]) pygame.display.update() self.loop() music.fadeout(500) pygame.time.wait(500) # FIXME Does this belong in the menu code? Probably. music.load(os.path.join(sound_path, "menu.ogg")) music.set_volume(1.0) music.play(4, 0.0) player_config.update(self._configs[0]) # Save p1's settings
def alarm(delay, times, song): mixer.init() if song == None: song = '/usr/share/cinnamon/sounds/bell.ogg' if times == 0: while True: time.sleep(time_converter(delay)) music.load(song) music.play(0) else: for i in range(times): time.sleep(time_converter(delay)) music.load(song) music.play(0)
def play_game_music(self): """Проигрывание музыки во время нахождения в игре""" if self.sound: for sound in self.sounds.values(): sound: Sound sound.stop() music.unpause() music.unload() music.load('music/background_tango_short.wav') music.set_volume(0.1) music.play(-1)
def __init__(self): music.load("../objs/torcidaASA.mp3") self.obj = GLuint() glEnable(GL_DEPTH_TEST) glEnable(GL_NORMALIZE) glEnable(GL_COLOR_MATERIAL) self.quad = gluNewQuadric() self.textura1 = '' self.axisX = 3.5 self.axisZ = -5 self.esqdir = 0 self.cimabaixo = 0 self.texturaID = GLuint() self._textureID = self.carrega_textura("../objs/soccer_ball.jpeg")
def play(self,file,cdImage=None,pos=0.0): ''' play a music file (file) show the cdImage(album art) if passed. ''' print "Starting playback of: "+file; self.meta=self.parseMetadata(file); music.load(file); if(cdImage!=None): img=pygame.image.load(cdImage); self.cdImg=pygame.transform.scale(img, (75,75)) else: self.cdImg=self.emptyCD; self.forceRefresh=True; music.play(0,pos);
def __init__(self, screen_size, map, bgmusic=None): pygame.init() #pygame.mixer.init() self.screen_size = screen_size self.screen = pygame.display.set_mode(screen_size) self.rect = self.screen.get_rect() self.clock = pygame.time.Clock() self.map = load_pygame(map) self.running = False self.group = pyscroll.PyscrollGroup() self.obstacles = pygame.sprite.Group() # Use pyscroll to ensure that the camera tracks the player and does # not go off the edge. map_data = pyscroll.TiledMapData(self.map) map_layer = pyscroll.BufferedRenderer( map_data, screen_size, clamp_camera=True) self.group = pyscroll.PyscrollGroup( map_layer=map_layer, default_layer=1) if bgmusic: self.music = music.load(bgmusic) print(bgmusic) else: self.music = None
def play(self): u"""音楽を再生する。ループに放り込んで使う""" if not self.stop: if not self.loopfile: if not self.looping and not music.get_busy(): music.play(self.loop) self.looping = True else: # イントロとループに分かれてる場合 if self.intro: # イントロ再生要求時 if not music.get_busy(): music.play() self.intro = False else: if not self.looping: if not music.get_busy(): music.load(self.loopfile) music.play(-1) self.looping = True
def set_music_enabled(state): global music_enabled if music_enabled != state: music_enabled = state if state: # Music pausing doesn't always seem to work. #music.unpause() if current_music: # After stopping and restarting currently loaded music, # fadeout no longer works. #print "albow.music: reloading", repr(current_music) ### music.load(current_music) music.play() else: jog_music() else: #music.pause() music.stop()
def __init__(self, config): self._config = config self._robots = dict() self._engine = Engine(self._config["engine"]) self._gp_robots = Group() self._gp_animations = Group() self._gp_shoots = Group() self._gp_overlays = Group() self._engine.add_group(self._gp_robots) self._engine.add_group(self._gp_animations) self._engine.add_group(self._gp_shoots) self._engine.add_group(self._gp_overlays) if self._config["system"]["capture"]: self._frames = [] self._teams = {} music.load(path.join(self._engine.resource_base_path, "sound", self._config["system"]["bg_music"]))
def update(self, time): if self._filename is None: pass elif time < self._start_time: pass elif not self._playing: try: music.stop() music.load(self._filename) music.set_volume(0.01) # 0.0 stops pygame.mixer.music. # Workaround for a pygame/libsdl mixer bug. #music.play(0, self._start) music.play(0, 0) self._playing = True except: # Filename not found? Song is too short? SMPEG blows? music.stop() self.playing = False elif time < self._start_time + 1000: # mixer.music can't fade in music.set_volume((time - self._start_time) / 1000.0) elif time > self._end_time - 1000: music.fadeout(1000) self._playing = False self._filename = None
def playmusic(_filename: str) -> None: """Play an MP3, WAV, or other audio files""" if PYGAME_IMPORTED: init() music.load(_filename) music.play() while music.get_busy() is True: continue elif is_program_aval(r'ffplay'): _process = Popen(shlex.split(r'ffplay -hide_banner -loglevel panic -sn -vn -nodisp ' + _filename), stdout=PIPE, stderr=PIPE) _stdout, _stderr = _process.communicate() elif is_program_aval(r'play'): _process = Popen(shlex.split(r'play -q -V1 ' + _filename), stdout=PIPE, stderr=PIPE) _stdout, _stderr = _process.communicate() elif _filename.endswith(r'.mp3') and is_program_aval(r'mpeg321'): _process = Popen(shlex.split(r'mpg321 --quiet ' + _filename), stdout=PIPE, stderr=PIPE) _stdout, _stderr = _process.communicate() elif _filename.endswith(r'.mp3') and is_program_aval(r'mpg123'): _process = Popen(shlex.split(r'mpg123 --quiet ' + _filename), stdout=PIPE, stderr=PIPE) _stdout, _stderr = _process.communicate() elif _filename.endswith(r'.ogg') and is_program_aval(r'ogg123'): _process = Popen(shlex.split(r'ogg123 --quiet ' + _filename), stdout=PIPE, stderr=PIPE) _stdout, _stderr = _process.communicate()
def start(self): music.load('games/pong/music.mp3') music.play(0, 0.5)
def main(): print "pydance", VERSION, "<*****@*****.**> - irc.freenode.net/#pyddr" if mainconfig["usepsyco"]: try: import psyco print _("Psyco optimizing compiler found. Using psyco.full().") psyco.full() except ImportError: print _("W: Psyco optimizing compiler not found.") # default settings for play_and_quit. mode = "SINGLE" difficulty = "BASIC" test_file = None for opt, arg in getopt(sys.argv[1:], "hvf:d:m:", ["help", "version", "filename=", "difficulty=", "mode="])[0]: if opt in ["-h", _("--help")]: print_help() elif opt in ["-v", _("--version")]: print_version() elif opt in ["-f", _("--filename")]: test_file = arg elif opt in ["-m", _("--mode")]: mode = arg elif opt in ["-d", _("--difficulty")]: difficulty = arg if test_file: play_and_quit(test_file, mode, difficulty) song_list = {} course_list = [] for dir in mainconfig["songdir"].split(os.pathsep): print _("Searching for songs in"), dir song_list.update(util.find_songs(dir, ['*.dance', '*.sm', '*.dwi', '*/song.*'])) for dir in mainconfig["coursedir"].split(os.pathsep): print _("Searching for courses in"), dir course_list.extend(util.find(dir, ['*.crs'])) screen = set_display_mode() pygame.display.set_caption("pydance " + VERSION) pygame.mouse.set_visible(False) try: if os.path.exists("/usr/share/pixmaps/pydance.png"): icon = pygame.image.load("/usr/share/pixmaps/pydance.png") else: icon = pygame.image.load(os.path.join(pydance_path, "icon.png")) pygame.display.set_icon(icon) except: pass music.load(os.path.join(sound_path, "menu.ogg")) music.play(4, 0.0) songs = load_files(screen, song_list.values(), _("songs"), SongItem, (False,)) # Construct the song and record dictionaries for courses. These are # necessary because courses identify songs by title and mix, rather # than filename. The recordkey dictionary is needed for player's # picks courses. song_dict = {} record_dict = {} for song in songs: mix = song.info["mix"].lower() title = song.info["title"].lower() if song.info["subtitle"]: title += " " + song.info["subtitle"].lower() if not song_dict.has_key(mix): song_dict[mix] = {} song_dict[mix][title] = song record_dict[song.info["recordkey"]] = song crs = load_files(screen, [course_list], _("courses"), courses.CourseFile, (song_dict, record_dict)) crs.extend(courses.make_players(song_dict, record_dict)) records.verify(record_dict) # Let the GC clean these up if it needs to. song_list = None course_list = None record_dict = None pad.empty() if len(songs) < 1: ErrorMessage(screen, (_("You don't have any songs or step files. Check out " "http://icculus.org/pyddr/get.php#songs " "and download some free ones. " "If you already have some, make sure they're in ")) + mainconfig["songdir"]) raise SystemExit(_("You don't have any songs. Check http://icculus.org/pyddr/get.php#songs .")) menudriver.do(screen, (songs, crs, screen)) # Clean up shit. music.stop() pygame.quit() mainconfig.write(os.path.join(rc_path, "pydance.cfg")) # FIXME -- is this option a good idea? if mainconfig["saveinput"]: pad.write(os.path.join(rc_path, "input.cfg")) records.write()
else: songList = randomizedList(list(orderedList)) start = 0 #Checks the last played position of the randomized list. if os.path.isfile(currentSong): if os.path.getsize(currentSong) > 0: currentSongFile = open(currentSong, 'r') start = int(currentSongFile.read()) currentSongFile.close() else: songList = randomizedList(list(orderedList)) #Plays every song in the song list from the starting position. for x in range(start, len(songList)): music.load(songList[x]) music.play() print("Now playing: " + getSongNameFromDirectoryName(songList[x])) switchSong = True #Writes the new position to the current song file. if os.path.isfile(currentSong): os.remove(currentSong) currentSongFile = open(currentSong, 'wb') currentSongFile.write(str(x)) currentSongFile.close() #Breaks out of this loop when the song ends to play the #next song. while switchSong: for event in pygame.event.get():
def exibe_musica(musica): music.load(musica) music.play()
def start(self): # TODO: Startup code here music.load(join('games','fall','fall.wav')) music.play()
s2.play(2) # optional parameter loops three times time.sleep(10) # set volume down s1.set_volume(0.1) time.sleep(5) # set volume up s1.set_volume(1) time.sleep(5) s1.stop() s2.stop() mixer.quit() # MP3 import time from pygame import mixer from pygame.mixer import music mixer.init() music.load('test.mp3') music.play() time.sleep(10) music.stop() mixer.quit() os.system("pause")
import os import time from pygame import mixer #I am using Pygame for this, though it would be nice to make a few different files to play from the built in player #Pygame can be downloaded from: http://www.pygame.org/download.shtml from pygame.mixer import music for i in os.listdir(os.getcwd()): #Goes through the folder. The current file is put in variable "i" if i.endswith(".wav"): #Looks for .wav file types. m4a files don't work with Pygame #mixer.init(frequency=16000) #Determines how high pitch the voice is played back. 16000 is normal mixer.init() music.load(i) #Loads the file that it is currently on ("i") to play music.play() #Plays the file time.sleep(3) #Delays the player to stop after X seconds music.stop() #stops the music mixer.quit() #Quits Pygame continue else: continue
def __init__(self, songs, courses, screen, game): InterfaceWindow.__init__(self, screen, "newss-bg.png") songs = [s for s in songs if s.difficulty.has_key(game)] if len(songs) == 0: error.ErrorMessage(screen, _("You don't have any songs for the game mode (") + game + _(") that you selected.")) #TODO: format using % for better i18n return # Construct a mapping between songs displays and dance displays. songs_and_dances = [(SongItemDisplay(s, game), [DanceItemDisplay(s, game, diff) for diff in s.diff_list[game]]) for s in songs] for (s,ds) in songs_and_dances: for d in ds: s.danceitems[d.diff]=d d.songitem=s self._songs = [s[0] for s in songs_and_dances] self._dances = reduce(lambda x,y: x+y[1],songs_and_dances,[]) self._index = 0 self._game = game self._config = dict(game_config) self._all_songs = self._songs self._all_dances = self._dances self._all_valid_songs = [s for s in self._songs if s.info["valid"]] self._all_valid_dances = [d for d in self._dances if d.info["valid"]] self._list = ListBox(FontTheme.SongSel_list, [255, 255, 255], 26, 16, 220, [408, 56]) # please use set constructions after python 2.4 is adopted sort_name = self._update_songitems() if len(self._songs) > 60 and mainconfig["folders"]: self._create_folders() self._create_folder_list() else: self._folders = None self._base_text = sort_name.upper() self._songitems.sort(key=SORTS[sort_name]) self._list.set_items([s.info["title"] for s in self._songitems]) self._preview = SongPreview() self._preview.preview(self._songitems[self._index]) self._song = self._songitems[self._index] # Both players must have the same difficulty in locked modes. self._locked = games.GAMES[self._game].couple players = games.GAMES[game].players # self._diffs = [] # Current difficulty setting self._diff_widgets = [] # Difficulty widgets self._configs = [] self._diff_names = [] # Current chosen difficulties self._pref_diff_names = [] # Last manually selected difficulty names self._last_player = 0 # Last player to change a difficulty for i in range(players): self._configs.append(dict(player_config)) d = DifficultyBox([84 + (233 * i), 434]) self._pref_diff_names.append(util.DIFFICULTY_LIST[0]) if not self._song.isfolder: self._diff_names.append(self._song.diff_list[0]) diff_name = self._diff_names[i] rank = records.get(self._song.info["recordkey"], diff_name, self._game)[0] grade = grades.grades[self._config["grade"]].grade_by_rank(rank) d.set(diff_name, DIFF_COLORS.get(diff_name, [127, 127, 127]), self._song.difficulty[diff_name], grade) else: self._diff_names.append(" ") d.set(_("None"), [127, 127, 127], 0, "?") self._diff_widgets.append(d) ActiveIndicator([405, 259], width = 230).add(self._sprites) self._banner = BannerDisplay([205, 230]) self._banner.set_song(self._song) self._sprites.add(HelpText(SS_HELP, [255, 255, 255], [0, 0, 0], FontTheme.help, [206, 20])) self._title = TextDisplay('SongSel_sort_mode', [210, 28], [414, 27]) self._sprites.add(self._diff_widgets + [self._banner, self._list, self._title]) self._screen.blit(self._bg, [0, 0]) pygame.display.update() self.loop() music.fadeout(500) pygame.time.wait(500) # FIXME Does this belong in the menu code? Probably. music.load(os.path.join(sound_path, "menu.ogg")) music.set_volume(1.0) music.play(4, 0.0) player_config.update(self._configs[0]) # Save p1's settings
def exibe_musica(diretoriomusica, nomemusica): music.load(os.path.join(diretoriomusica, nomemusica)) music.play(-1)