Пример #1
0
def sync_play_time(self, pitch_timestamp, old_time):
    # sleep
    deta_time = time.time() - old_time
    deta_timestamp = pitch_timestamp - self.last_timestamp
    wait_time = int(deta_timestamp * parse_midi.g_mseconds_per_quarter / parse_midi.g_ticks_per_quarter )
    # print "---- midi need wait:", wait_time

    ## show before play
    deta_time = time.time() - old_time
    if wait_time - deta_time*1000 > 10:
        self.gl_screen_blit()
        pygame.display.flip()
    deta_time = time.time() - old_time
    # print "after pygame:", int(deta_time*1000)

    for cmd, pitch, volecity in self.play_commands:
        if cmd == "NOTE_ON":
            player.play(pitch, volecity, self.sounds)
        elif cmd == "NOTE_OFF":
            player.stop(pitch, volecity, self.sounds)
        elif cmd == "METRO_ON" and player.g_metronome_volume > 0:
            player.play(pitch, volecity, self.sounds)
    deta_time = time.time() - old_time
    # print "after play:", int(deta_time*1000)

    player.real_stop(self.sounds, wait_time/1000.0 - deta_time - 0.03)
    deta_time = time.time() - old_time
    # print "after stop:", int(deta_time*1000)

    if wait_time/1000.0 - deta_time > 0:
        time.sleep((wait_time/1000.0 - deta_time))
Пример #2
0
    def post(self):
      data = self.request.get('input')
      logging.error("data")

      if data == "pause" or data == "play":
          player.pause()
      elif data == "ffwd30":
          player.fastfwd30()
      elif data == "rwnd30":
          player.rewind30()
      elif data == "volup":
          player.volume_up()
      elif data == "voldown":
          player.volume_down()
      elif data == "stop":
          player.stop()
          self.redirect("/explorer")
          return
      elif data == "next":
          player.next_chapter()
      elif data == "previous":
          player.previous_chapter()
      elif data == "info":
          player.info()
      else :
          player.stop()
          self.redirect("/explorer")
          return



      self.redirect("/remote")
Пример #3
0
 def remove(self, pos):
     if self.is_valid_position(pos):
         del self.queue[pos]
         if self.position > pos:
             self.position -= 1
         elif self.position == pos:
             player.stop()
     return self.get_queue()
Пример #4
0
 def remove(self, pos):
     if self.is_valid_position(pos):
         del self.queue[pos]
         if self.position > pos:
             self.position -= 1
         elif self.position == pos:
             player.stop()
     return self.get_queue()
Пример #5
0
def on_exit():
    """When you click to exit, this function is called"""
    if messagebox.askyesno("Exit", "Do you want to quit the application?"):
        root.destroy()
        player.stop()
        try:
            shutil.rmtree('./tmp')
        except:
            print("can't delite tmp")
        raise SystemExit
Пример #6
0
 def remove_song(self, song_id, skip=False):
     """Removes the packet with the given id"""
     session = Session()
     packet = session.query(Packet).filter_by(song_id=song_id).first()
     if isinstance(player.now_playing, Song) and player.now_playing.id == song_id:
         player.stop()
         if skip:
             self.virtual_time = packet.finish_time
     session.delete(packet)
     session.commit()
     self._update_active_sessions()
     return self.get_queue()
Пример #7
0
 def remove_video(self, url, skip=False):
     """Removes the packet with the given video_url"""
     session = Session()
     packet = session.query(Packet).filter_by(video_url=url).first()
     if isinstance(player.now_playing, YouTubeVideo) and player.now_playing.url == url:
         player.stop()
         if skip:
             self.virtual_time = packet.finish_time
     session.delete(packet)
     session.commit()
     self._update_active_sessions()
     return self.get_queue()
Пример #8
0
 def remove_song(self, song_id, skip=False):
     """Removes the packet with the given id"""
     session = Session()
     packet = session.query(Packet).filter_by(
         song_id=song_id, player_name=PLAYER_NAME).first()
     if (isinstance(player.now_playing, Song)
             and player.now_playing.id == song_id):
         player.stop()
         if skip:
             self.virtual_time = packet.finish_time
     session.delete(packet)
     session.commit()
     self._update_active_sessions()
     return self.get_queue()
Пример #9
0
 def remove_video(self, url, skip=False):
     """Removes the packet with the given stream_url"""
     session = Session()
     packet = session.query(Packet).filter_by(
         stream_url=url, player_name=PLAYER_NAME).first()
     if (isinstance(player.now_playing, YouTubeVideo)
             and player.now_playing.url == url):
         player.stop()
         if skip:
             self.virtual_time = packet.finish_time
     elif (isinstance(player.now_playing, SoundCloudMusic)
           and player.now_playing.url == url):
         player.stop()
         if skip:
             self.virtual_time = packet.finish_time
     session.delete(packet)
     session.commit()
     self._update_active_sessions()
     return self.get_queue()
Пример #10
0
Файл: web.py Проект: lorc/belyn
def player_cmd(request):
    if not player.playing():
        request.session.flash(u"А плеер то не играет!")
        return HTTPFound(location=request.route_url('player'))

    cmd = request.matchdict["cmd"]
    if cmd=="pause":
        player.pause()
    elif cmd=="stop":
        player.stop()
    elif cmd=="seek_left":
        player.seek(-5)
    elif cmd=="seek_right":
        player.seek(5)
    elif cmd=="snd_up":
        player.volume(5)
    elif cmd=="snd_down":
        player.volume(-5)
    else:
        request.session.flash(u"Не знаю что за команда")
    return HTTPFound(location=request.route_url('player'))
Пример #11
0
Файл: main.py Проект: th28/RPG
def main():
    pygame.mixer.pre_init(44100,-16,2,2048)
    pygame.mixer.init()
    pygame.init()
    screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT),pygame.FULLSCREEN)
    players = pygame.sprite.Group()
   
    npcs = pygame.sprite.Group()
    
    player = Player(960,0,"1.png",100,"Tom","elf")
    players.add(player)
    
    myStates = StateMachine()

    clock = pygame.time.Clock()
    #1920,960
    camera = Camera(complex_camera,1920,960)
    
    
    myWorld = World(players,npcs,screen,player,camera)
    diag = None
  
    interface = Interface(screen,player,myQuests)
    
    npcs.add(milton)
    npcs.add(jwood)
    myStates.addState("WORLD_STATE",myWorld)
    myStates.addState("INTF_STATE",interface)
    myStates.addState("DIAG_STATE",diag)
    
    keepGoing = True
    counter = 0
    
    currentState = "WORLD_STATE"

    manager = StateChangeManager(currentState,player)


    pygame.joystick.init()
    mypad = pygame.joystick.Joystick(0)
    mypad.init()
    
    
    
    while keepGoing:
        
        clock.tick(30)
        #print clock.get_fps()
        player.update(myWorld,dialog,manager,npcs,myStates)
        myStates.renderState(manager.getCurrentState(),manager)
        
        q1.update()
        myQuests.update()

        
        
        if mypad.get_axis(0) < -.8:
            
            player.go_down_left()
 
        elif player.change_x < 0 or player.change_y > 0:

            player.stop('xy')
            
        
           
        if mypad.get_axis(0) > .8:

            player.go_up_right()

            
        elif player.change_x > 0 or player.change_y < 0:
            player.stop('xy')
        
        #------------------------#
        
        if mypad.get_axis(1) < -.8:

            player.go_up_left()
        
        if mypad.get_axis(1) > .8:

            player.go_down_right()

        
                        
        
        if mypad.get_axis(0) > .7 and mypad.get_axis(1) > .7:
            print "fork"
            player.stop('xy')
            player.go_right()

        if mypad.get_axis(0) < -.7 and mypad.get_axis(1) > .7:
            print "fork"
            player.stop('xy')
            player.go_down()

        if mypad.get_axis(0) < -.7 and mypad.get_axis(1) < -.7:
            player.stop('xy')
            player.go_left()

        if mypad.get_axis(0) > .7 and mypad.get_axis(1) < -.7:
            player.stop('xy')
            player.go_up()
        
        
            
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if manager.getCurrentState() == "WORLD_STATE":
                    
                    if (event.key == K_a):
                        
                            
                        player.go_left()
                    
                    if (event.key == K_d):
                        
                    
                        player.go_right()
                    
                    if (event.key == K_s):
                        
                    
                        player.go_down()
                    
                    if (event.key == K_w):
                        
                    
                        player.go_up()
                        
                    if (event.key == K_e):

                        player.interact()

                if (event.key == K_m):
                    if manager.getCurrentState() == "WORLD_STATE":
                        manager.changeState("INTF_STATE")
                    
            if event.type == KEYUP:
                if event.key == pygame.K_a and player.change_x < 0:
                    player.stop("x")
                   
                if event.key == pygame.K_d and player.change_x > 0:
                    player.stop("x")
                    
                if event.key == pygame.K_w and player.change_y < 0:
                    player.stop("y")
                    
                if event.key == pygame.K_s and player.change_y > 0:
                    player.stop("y")
                    
                if event.key == pygame.K_e:
     
                    player.uninteract()
                    
            if event.type == QUIT:
                pygame.quit()
                sys.exit(0)
        
            
        pygame.display.update()
Пример #12
0
     else:
         surface.blit(battleField, (0, 0))
     for idx, player in enumerate(playersFighting):
         player.atackMoment(GAME_TIME)
         player.drawLives(surface)
         player.move(GAME_TIME)
         player.drawSword(surface)
         player.drawPlayer(surface, GAME_TIME, roundFinished)
         if idx == 1:
             otherPlayerIndex = 0
         else:
             otherPlayerIndex = 1
         player.receiveArrow(playersFighting[otherPlayerIndex])
         if player.imDead():
             roundFinished = True
             player.stop('True')
             if triforceWaiting == 0:
                 triforceWaiting = 1
         if roundFinished == True and player.imDead() == False:
             player.stop('True')
             if triforceWaiting == 1 and roundFinished:
                 finalMoment = GAME_TIME.get_ticks()
                 triforceWaiting = 2
             if GAME_TIME.get_ticks() - finalMoment >= 5000:
                 player.stop('False')
 for event in GAME_EVENTS.get():
     if event.type == pygame.KEYDOWN:
         if menu:
             if event.key == pygame.K_SPACE:  #para salir del menu
                 menu = False
                 modeSelector = 0
Пример #13
0
 def clear(self):
     session = Session()
     session.query(Packet).delete()
     session.commit()
     player.stop()
     return self.get_queue()
Пример #14
0
 def stop(self):
     """
     Stop the current playing
     """
     audioplayer.stop()
Пример #15
0
def power_button_pressed():
    print("power pressed")
    player.stop()
    reset_last_code()
Пример #16
0
def main():
    root.title('Perceptual audio quality assessment')

    samples = glob(os.path.join(SAMPLES_PATH, '*.wav'))
    loaded_samples = [load_wav(sample) for sample in samples]
    user_scores_variables = {
        # 'group': [
        #     'id': variable
        # ]
    }

    if len(samples) == 0:
        print('No samples found')
        exit(1)

    samplesListBox = Listbox(root)
    samplesListBox.insert(0, *samples)
    samplesListBox.select_set(0)
    samplesListBox.pack(fill='both', expand=True, padx=10, pady=10)

    def selected_sample_name():
        return os.path.splitext(
            os.path.split(samples[samplesListBox.curselection()[0]])[-1])[0]

    def selected_sample_np_array():
        return loaded_samples[samplesListBox.curselection()[0]]

    Button(root,
           text='Stop playing',
           highlightbackground='green',
           command=player.stop).pack(fill='both', expand=True)

    Separator().pack(pady=5, fill='both')

    Button(root,
           text='Play and plot the original (16-bit, 44.1 kHz)',
           command=lambda: show_plot_and_play(selected_sample_np_array(
           ), BASE_SAMPLING_RATE)).pack(fill='both', expand=True)

    Separator().pack(pady=5, fill='both')

    user_scores_variables['quantization'] = [
        (num_bits,
         button_with_score(
             root,
             text=f'Play and plot quantized to {num_bits}-bit',
             command=lambda num_bits=num_bits: show_plot_and_play(
                 quantize(selected_sample_np_array(), num_bits),
                 BASE_SAMPLING_RATE, selected_sample_np_array())))
        for num_bits in QUANTIZATION_VARIANTS
    ]

    Separator().pack(pady=5, fill='both')

    user_scores_variables['sampling_rate'] = [
        (sampling_rate,
         button_with_score(
             root,
             text=
             f'Play and plot interpolated to {round(sampling_rate/1000)} kHz',
             command=lambda sampling_rate=sampling_rate: show_plot_and_play(
                 change_sampling_rate(selected_sample_np_array(
                 ), BASE_SAMPLING_RATE, sampling_rate), sampling_rate,
                 selected_sample_np_array())))
        for sampling_rate in SAMPLING_RATE_VARIANTS
    ]

    Separator().pack(pady=5, fill='both')

    user_scores_variables['compression'] = [
        ('A-law',
         button_with_score(
             root,
             text='Play and plot after A-law compression',
             command=lambda: show_plot_and_play(
                 a_law_compress(selected_sample_np_array(), 2),
                 BASE_SAMPLING_RATE, selected_sample_np_array()))),
        ('u-law',
         button_with_score(
             root,
             text='Play and plot after μ-law compression',
             command=lambda: show_plot_and_play(
                 u_law_compress(selected_sample_np_array(), 2),
                 BASE_SAMPLING_RATE, selected_sample_np_array()))),
        ('ADPCM',
         button_with_score(
             root,
             text='Play and plot after ADPCM compression',
             command=lambda: show_plot_and_play(
                 adpcm_compress(selected_sample_np_array(), 2),
                 BASE_SAMPLING_RATE, selected_sample_np_array())))
    ]

    Separator().pack(pady=5, fill='both')

    Button(root,
           text='Save perceptual score for selected file',
           command=lambda: save_scores(selected_sample_name(),
                                       user_scores_variables),
           highlightbackground='cyan').pack(fill='both', expand=True)

    root.mainloop()
    player.stop()
Пример #17
0
 def clear(self):
     session = Session()
     session.query(Packet).filter_by(player_name=PLAYER_NAME).delete()
     session.commit()
     player.stop()
     return self.get_queue()
Пример #18
0
                if event.key == pygame.K_LEFT:
                    player.move("left")
                elif event.key == pygame.K_RIGHT:
                    player.move("right")
                elif event.key == pygame.K_UP:
                    player.move("up")
                elif event.key == pygame.K_DOWN:
                    player.move("down")
                elif event.key == pygame.K_p:
                    menus.pause()
                elif event.key == pygame.K_w:
                    done = True

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    player.stop("left")
                elif event.key == pygame.K_RIGHT:
                    player.stop("right")
                elif event.key == pygame.K_UP:
                    player.stop("up")
                elif event.key == pygame.K_DOWN:
                    player.stop("down")

        temp.update(constants.display_surface)
        player.update()

    if state == 1:
        pass

    constants.clock.tick(constants.FPS)
    pygame.display.update()
Пример #19
0
    def main(self):
        """Play a midi file with sound samples
        """
        player.init()
        clock = pygame.time.Clock()
        old_time = 0
        p_done = False

        pitch_offset = 60
        need_update_display = True
        while not p_done:
            # events
            for ev in pygame.event.get():
                need_update_display = True
                menu_bar_screen = self.menu_bar.update(ev)
                if self.menu_bar:
                    self.menu_bar_info.set(self.get_menus_info_bar())
                    # self.menu_bar_info.update(ev)

                if self.menu_bar.choice:
                    try:
                        self.load_resource(self.menu_bar.choice_label[-1])
                    except Exception, e:
                        print "menu error:", e
                    # if have choice, continue event
                    continue

                if ev.type == MOUSEBUTTONUP:
                    if ev.pos[1] > 60:
                        continue
                    # enable/disable tracks
                    for track_idx in self.enabled_tracks:
                        sw = self.enabled_tracks_switch[track_idx]
                        if sw.collidepoint(ev.pos):
                            self.enabled_tracks[track_idx] = not self.enabled_tracks[track_idx]

                            idx = self.tracks_order_idx[track_idx]
                            note_color = self.piano.TRACK_COLORS[idx % len(self.piano.TRACK_COLORS)]
                            if self.enabled_tracks[track_idx]:
                                self.piano.screen.fill(note_color, sw)
                            else:
                                self.piano.screen.fill(self.piano.color_lines, sw)

                elif ev.type == MOUSEBUTTONDOWN:
                    if ev.button == 5: # scroll down
                        self.staff_offset_x += 40

                    elif ev.button == 4: # scroll up
                        self.staff_offset_x -= 40
                        if self.staff_offset_x < 0:
                            self.staff_offset_x = 0

                    elif ev.button == 3: # right button
                        self.is_pause = not self.is_pause

                    elif ev.button == 1:   # left button
                        if ev.pos[1] < 60: # progress bar can not click
                            continue
                        clicked_staff_number = int((ev.pos[1] - self.staff_top) / (self.piano.staff_total_lines * self.piano.staff_space_height))
                        wraped_staff_offset = 0
                        if clicked_staff_number > 0:
                            wraped_staff_offset += self.piano.lastbar_pos_in_line1
                        if clicked_staff_number > 1:
                            wraped_staff_offset += self.piano.lastbar_pos_in_line2 * (clicked_staff_number-1)

                        timestamp_offset_x = (
                            self.staff_offset_x +
                            ev.pos[0] +
                            wraped_staff_offset
                        ) * self.piano.timestamp_range / self.screen_rect.width

                        self.last_timestamp = -1
                        for idx, midi_line in enumerate(self.all_midi_lines):
                            cmd, pitch, volecity_data, track_idx, pitch_timestamp = midi_line[:5]
                            if timestamp_offset_x > pitch_timestamp:
                                if self.last_timestamp != pitch_timestamp:
                                    self.midi_cmd_idx = idx
                                    self.last_timestamp = pitch_timestamp
                            elif timestamp_offset_x < pitch_timestamp:
                                break

                        self.play_one_timestamp_while_paused = True
                        self.piano.reset_piano()


                elif ev.type == KEYUP:
                    if ev.key == K_ESCAPE:
                        p_done = True
                        break

                    # MENU Reload
                    elif ev.key == K_RETURN:
                        menus_in_bar, self.midi_filename_data = get_menu_data()
                        self.menu_bar.set(menus_in_bar)

                    # Stop
                    elif ev.key == K_s:
                        self.piano.reset_piano()
                        self.staff_offset_x = 0
                        self.midi_cmd_idx = 0
                        self.last_timestamp = -1
                        self.is_pause = True

                    # Pause/Play
                    elif ev.key == K_SPACE:
                        self.is_pause = not self.is_pause

                    # is_longbar_show
                    elif ev.key == K_c:
                        self.piano.is_longbar_show = not self.piano.is_longbar_show

                    elif ev.key == K_COMMA:
                        # Slower
                        parse_midi.g_mseconds_per_quarter = int(60000 / (
                            60000 / parse_midi.g_mseconds_per_quarter - 10))
                        if parse_midi.g_mseconds_per_quarter > 2000:
                            parse_midi.g_mseconds_per_quarter = 2000
                        self.menu_bar_info.set(self.get_menus_info_bar())
                    elif ev.key == K_PERIOD:
                        # Faster
                        parse_midi.g_mseconds_per_quarter = int(60000 / (
                            60000 / parse_midi.g_mseconds_per_quarter + 10))
                        if parse_midi.g_mseconds_per_quarter <= 200:
                            parse_midi.g_mseconds_per_quarter = 200
                        self.menu_bar_info.set(self.get_menus_info_bar())

                    #Page_Up/Page_Down
                    elif ev.key == K_DOWN:
                        self.staff_offset_x += self.piano.lastbar_pos_in_line1
                    elif ev.key == K_UP:
                        self.staff_offset_x -= self.piano.lastbar_pos_in_line1
                        if self.staff_offset_x < 0:
                            self.staff_offset_x = 0

                    # Previous/Next MIDI
                    elif ev.key in [K_LEFT, K_RIGHT]:
                        need_reload = False
                        if ev.key == K_LEFT:
                            if self.midi_filename_idx > 0:
                                self.midi_filename_idx -= 1
                                need_reload = True
                        elif ev.key == K_RIGHT:
                            if self.midi_filename_idx+1 < len(self.midi_filename_data):
                                self.midi_filename_idx += 1
                                need_reload = True
                        if need_reload:
                            midi_filename = self.midi_filename_data[self.midi_filename_idx]
                            self.load_resource(midi_filename)

                    # Metronome
                    elif ev.key == K_m:
                        if (1.0 - player.g_metronome_volume) / 2 < 0.1:
                            player.g_metronome_volume += 0.1
                        else:
                            player.g_metronome_volume += (1.0 - player.g_metronome_volume) / 2

                    # # Set Progress Percent
                    # elif ev.key in [K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9]:
                    #     self.piano.reset_piano()
                    #     self.midi_cmd_idx = self.all_midi_lines_length * (ev.key - 48) / 10
                    #     self.last_timestamp = -1

                    # Set Pitch Offset
                    elif ev.key in [K_v, K_b, K_n]:
                        pitch_offset = {K_v: 36,  K_b: 60,  K_n: 84}[ev.key]

                    elif ev.key == K_f:
                        player.g_volecity_adjust = (player.g_volecity_adjust+1) % len(player.g_volecity_list)
                        player.load_sounds([(midi_data[1], midi_data[2]) for midi_data in self.all_midi_lines],
                                           self.sounds)

                    elif ev.key == K_z:
                        if self.piano.staff_space_height > 2:
                            self.piano.staff_space_height /= 2
                        self.piano.timestamp_range = TIMESTAMP_RANGE * parse_midi.g_ticks_per_quarter / parse_midi.g_mseconds_per_quarter
                        self.piano.timestamp_range = self.piano.timestamp_range * self.piano.staff_space_height_base / self.piano.staff_space_height
                    elif ev.key == K_x:
                        if self.piano.staff_space_height < 128:
                            self.piano.staff_space_height *= 2
                        self.piano.timestamp_range = TIMESTAMP_RANGE * parse_midi.g_ticks_per_quarter / parse_midi.g_mseconds_per_quarter
                        self.piano.timestamp_range = self.piano.timestamp_range * self.piano.staff_space_height_base / self.piano.staff_space_height

                    # Play Piano with keys
                    elif ev.key in PITCH_OF_KEY_ON_KEYBOARD:
                        pitch = pitch_offset + PITCH_OF_KEY_ON_KEYBOARD.index(ev.key)
                        player.stop(pitch, 100, self.sounds)
                        player.load_sounds([(pitch, 100)], self.sounds)
                        cmd = "NOTE_OFF"
                        self.piano.show_keys_press(cmd, pitch)

                elif ev.type == KEYDOWN:
                    if ev.key in PITCH_OF_KEY_ON_KEYBOARD:
                        pitch = pitch_offset + PITCH_OF_KEY_ON_KEYBOARD.index(ev.key)
                        player.load_sounds([(pitch, 100)], self.sounds)
                        player.play(pitch, 100, self.sounds)
                        cmd = "NOTE_ON"
                        self.piano.show_keys_press(cmd, pitch)

            # must out of events loop
            if self.menu_bar or self.menu_bar.choice:
                self.gl_screen_blit()
                pygame.display.flip()
                clock.tick(10)
                continue

            # get cmd
            try:
                if (self.is_pause and not self.play_one_timestamp_while_paused):
                    raise Exception("paused")
                # repeat
                if self.midi_cmd_idx >= self.all_midi_lines_length:
                    raise Exception("repeat")

                midi_line = self.all_midi_lines[self.midi_cmd_idx]
                self.midi_cmd_idx += 1
                cmd, pitch, volecity_data, track_idx, pitch_timestamp = midi_line[:5]
                volecity = player.get_volecity(volecity_data)
                if pitch not in [0, 1] + player.g_grand_pitch_range:
                    continue
                if track_idx >= 0 and not self.enabled_tracks.get(track_idx, False):
                    continue
                if self.last_timestamp == -1:
                    # init last timestamp
                    self.last_timestamp = pitch_timestamp - 1
            except Exception, e:
                if need_update_display:
                    self.piano.show_notes_staff_in_page(self.enabled_tracks, self.tracks_order_idx,
                                            self.notes_in_all_staff, self.last_timestamp,
                                            self.staff_top,
                                            parse_midi.g_bar_duration,
                                            parse_midi.g_time_signature_n,
                                            self.staff_offset_x, self.is_pause)
                    has_stoped = player.real_stop(self.sounds)
                    self.gl_screen_blit()
                    pygame.display.flip()
                    need_update_display = False

                if self.midi_cmd_idx >= self.all_midi_lines_length:
                    if self.midi_repeat_count < TRAINING_REPEAT_TIMES:
                        self.midi_repeat_count += 1
                        self.staff_offset_x = 0
                        self.midi_cmd_idx = 0
                        self.last_timestamp = -1
                    else:
                        if self.midi_filename_idx+1 < len(self.midi_filename_data):
                            self.midi_filename_idx += 1
                        else:
                            self.midi_filename_idx = 0
                        midi_filename = self.midi_filename_data[self.midi_filename_idx]
                        self.load_resource(midi_filename)
                        self.is_pause = False

                clock.tick(40)
                continue
Пример #20
0
def update(dt):
    global rdown, ldown, udown, ddown, pdown, frame

    frame += 1

    if is_snapped(player): #If on the grid
        player.stop() #Stop moving

        pressing = False

        #Rotate if movement keys are pressed
        if rdown and not ldown:
            SPRITES.get("player").rotation=90
            player.hfacing = 1
            player.vfacing = 0
            pressing = True
        elif ldown and not rdown:
            SPRITES.get("player").rotation=270
            player.hfacing = -1
            player.vfacing = 0
            pressing = True
        elif udown and not ddown:
            SPRITES.get("player").rotation=0
            player.hfacing = 0
            player.vfacing = 1
            pressing = True
        elif ddown and not udown:
            SPRITES.get("player").rotation=180
            player.hfacing = 0
            player.vfacing = -1
            pressing = True

        bl = get_entity(player.x + player.hfacing*constants.TILE_SIZE, player.y + player.vfacing*constants.TILE_SIZE,"block")
        bl2 = get_entity(player.x + player.hfacing*constants.TILE_SIZE*2, player.y + player.vfacing*constants.TILE_SIZE*2,"block")

        if bl is None:
            if pressing:
                player.hspeed = player.hfacing * constants.PLAYER_SPEED
                player.vspeed = player.vfacing * constants.PLAYER_SPEED
                player.step() # On the grid and free space ahead
        elif pdown:
            if not bl.is_moving():
                if not bl2 is None:
                    if bl.crushed == 0:
                        snd_crush.play()
                        bl.crush()
                else:
                    bl.get_pushed(player.hfacing,player.vfacing)
                    snd_shoot.play()

    else: #If not on the grid
        player.step() # Not on the grid, nowhere to go but forward

 


    for b in things:
        if b.looks_like == "block":
            if b.crushed >= 1:
                things.remove(b)
                continue

            f = get_entity(b.x + constants.TILE_SIZE + b.hspeed, b.y + constants.TILE_SIZE + b.vspeed,"block")

            if b.is_moving() and not f is None and not f is b:
                b.collide_with(f)
                #snd_bounce.play()
                print(str(b) + " collided with " + str(f))


            b.update()

    
    #Stop player from going out of bounds
    if player.x < 0:
        player.x = 0
        player.stop()
    if player.y < 0:
        player.y = 0
        player.stop()
    if player.x > constants.WINDOW_WIDTH-constants.TILE_SIZE:
        player.x = constants.WINDOW_WIDTH-constants.TILE_SIZE
        player.stop()
    if player.y > constants.WINDOW_HEIGHT-constants.TILE_SIZE:
        player.y = constants.WINDOW_HEIGHT-constants.TILE_SIZE
        player.stop()
Пример #21
0
def game(score_state):
	# No sound. :(
        #pygame.mixer.pre_init(44100,8,4,1024)
        pygame.init()
        pygame.font.init()
        #pygame.mixer.music.set_volume(2.0)
#        if pygame.mixer.music.get_busy():
#                pass
#        else:
#                musicfile = data.filepath('midi','bumblbee.mid')
#                pygame.mixer.music.load(musicfile)
#                pygame.mixer.music.play(-1)
	
	screen = pygame.display.set_mode(SCREENRECT.size)
	clock = pygame.time.Clock()
	background = pygame.image.load(data.filepath('images/new_background.png')).convert()
	level = Level()

	tornadoes = pygame.sprite.Group()
	houses = pygame.sprite.Group()
	player = pygame.sprite.Group()
	rays = pygame.sprite.Group()
	lightnings = pygame.sprite.Group()
	all = pygame.sprite.OrderedUpdates()
	titles = pygame.sprite.Group()
	statuses = pygame.sprite.Group()
	scores = pygame.sprite.Group()
	sparks = pygame.sprite.Group()
	
	start_new_game = False

	Score.containers = all
	Status.containers = all
	Title.containers = all
	Tornado.containers = tornadoes,all
	House.containers = houses,all
	Ray.containers = rays,all
	Lightning.containers = lightnings,all
	Score.containers = all
	Spark.containers = all
	Status.containers = all
	Player.containers = all

	screen.blit(background,(0,0))
        pygame.display.flip()

	# Title Screen
	score = Score(score_state)
	status_pause = 0
	first_time = True

        while start_new_game == False:
                status_pause = status_pause + 1
                if (first_time):
                        title_text = "Twisted Twister!"
                        Title(title_text,(0,0,0))
                        Title(title_text,(255,0,0))
                        Title(title_text,(0,255,255))
                        Title(title_text,(0,255,0))
                        Title(title_text,(0,0,255))
                        first_time = False
                for event in pygame.event.get():
                        if event.type == QUIT:
                                sys.exit()
                        if event.type == MOUSEBUTTONDOWN:
                                start_new_game = True
                        if event.type == KEYDOWN:
                                if event.key == K_ESCAPE:
                                        sys.exit()
                                else:
                                        start_new_game = True

                if status_pause > 100:
			Status ("Press any key to start...")
                        status_pause = 0
                all.clear(screen,background)
                all.update()
                dirty = all.draw(screen)
                pygame.display.update(dirty)
                clock.tick(30)
	kill_objects(all)

	house_container = []
	# Stuff to do to start the game
	#for i in range(100,800,150):
	for i in range(0,5):
		house_container.append(House(((i*150)+100,500)))

	# Reset the level
	level.start()

	# Start the scoreboard
	score = Score(score_state)

	# Populate the screen with the actors
	fujita = start_game(level)
	player = Player((400,550))

	# Lights! Camera! Silence on the set!
	playing = True
	bonus_house = 0
	last_bonus = 0
	bonus_at = 10000

	# Cameras rolling...
	# 3...2...1... Action!
	while playing:
		active = True
		lightning_counter = 0
		Status("Level %d, %s spotted!" % (level.get_level(), 'F' + str(fujita) + 's'))
		if (bonus_house > 0):
			for t in range(0,5):
				if (house_container[t].is_alive() == False):
					if (bonus_house >= 1):
						house_container[t].set_alive()
						bonus_house = bonus_house - 1
		while active:
			lightning_counter = lightning_counter + 1
			if lightning_counter > min(300,10000 - (level.get_level() * 200)):
				Lightning(player.get_position()) 
				lightning_counter = 0
			for event in pygame.event.get():
				if event.type == QUIT:
					sys.exit()
				if event.type == KEYDOWN:
					# Put in an escape key / Q key handler
					if event.key == K_ESCAPE:
						active = False
						playing = False
					if event.key == K_LEFT:
						player.left()
					if event.key == K_RIGHT:
						player.right()
					if event.key == K_LCTRL or event.key == K_RCTRL:
						player.fire()
				if event.type == KEYUP:
					if event.key == K_LEFT:
						player.stop()
					if event.key == K_RIGHT:
						player.stop()
					pass

			tornado_house_collide = pygame.sprite.groupcollide(houses,tornadoes,False,False)
			if (tornado_house_collide):
				for house in (tornado_house_collide):
					for tornado in (tornado_house_collide[house]):
						if (house.is_alive()):
							tornado.rise()
							house.rise(tornado.get_fujita())
			tornado_ray_collide = pygame.sprite.groupcollide(tornadoes,rays,False,False)
			if (tornado_ray_collide):
				for tornado in (tornado_ray_collide):
					tornado.hit(score)
			if (not tornadoes.sprites()):
				active = False
			lightning_player_collide = pygame.sprite.spritecollide(player,lightnings,False)
			if (lightning_player_collide):
				player.hit()
				Spark(player.get_midtop_position())

			if (score.get_score() >= (last_bonus + bonus_at)):
				bonus_house = bonus_house + 1
				# Should return the last score at 10,000 increments
				last_bonus = (score.get_score() / 1000) * 1000
				Status("Bonus!")
			all.clear(screen,background)
			all.update() 
			dirty = all.draw(screen) 
			pygame.display.update(dirty)
			clock.tick(30)

		# Reset for the next level
		if playing:
			level.next_level()	
			player.kill()
			fujita = start_game(level)
			player = Player((400,550))
			lightning_counter = 0
			houses_alive = False
			for i in range(0,5):
				house_container[i].restoration()
				houses_alive = houses_alive or house_container[i].is_alive()
			if (houses_alive or bonus_house > 0):
				playing = True
				active = True
			else:
				active = False
				playing = False
	score_state = score.get_score_state()
	kill_objects(all)
	return (score_state)
Пример #22
0
def main(excel_file, audio_path):
    # initialise variables
    main.audio_path = audio_path
    input_file = excel_file
    data = ExcelImport(input_file)
    main.input_array = data.array()
    data.ncd.append('Uncategorised')
    main.input_ncd = data.ncd
    main.dict = {}

    # tkinkter window options
    main.root = Tk()
    main.root.protocol("WM_DELETE_WINDOW", disable_event)
    main.root.title("DJ library editor")

    # get details from ID3 for audio file
    id3_output = ID3Editor.main_id3(audio_path)
    main.cat = id3_output[0]
    main.key = id3_output[1]
    main.energy = id3_output[2]
    details = ID3Editor.get_details(audio_path)
    song_title = details[0]
    artist = details[1]

    # start playback of file on open
    play(audio_path)

    # copy category list so program can later determine leftover categories
    main.leftover_cat = copy.copy(main.cat)

    # initalise string update in window
    main.update = StringVar()

    # draw labels
    fm = Frame(main.root)
    for item in main.input_ncd:
        Label(fm, text=item, relief=GROOVE, bd=5).pack(side=TOP,
                                                       anchor=W,
                                                       fill=X)
    fm.pack(side=LEFT, padx=10)

    # check categories for leftovers and remove used categories from leftover_cat
    for list in main.input_array:
        for item in list:
            for value in main.cat:
                if value == item:
                    main.leftover_cat.remove(value)
    main.input_array.append(main.leftover_cat)
    """Uncomment to see remaining cat in list"""
    """print(main.leftover_cat)"""

    # draw checkboxes
    fm2 = Frame(main.root)
    i = 0
    for item in main.input_array:
        main.dict[main.input_ncd[i]] = Checkbar(fm2, item)
        main.dict[main.input_ncd[i]].pack(side=TOP, anchor=W, fill=X)
        main.dict[main.input_ncd[i]].config(relief=GROOVE, bd=1)
        i += 1
    fm2.pack(side=LEFT, padx=10)

    # draw user buttons
    fm3 = Frame(main.root)
    Button(fm3, text='Next',
           command=lambda: close_inst(audio_path)).pack(side=RIGHT)
    Button(fm3, text='Check states', command=allstates).pack(side=RIGHT)
    Button(fm3, text='Write', command=lambda: write()).pack(side=RIGHT)
    Button(fm3, text="Play", command=lambda: play(audio_path)).pack(side=RIGHT)
    Button(fm3, text="Stop", command=lambda: stop(audio_path)).pack(side=RIGHT)
    fm3.pack(side=RIGHT, padx=10)

    # draw eyed3 info labels
    fm4 = Frame(main.root)
    Label(fm4, text=audio_path, relief=GROOVE, bd=2).pack(side=BOTTOM,
                                                          anchor=W,
                                                          fill=X)
    Label(fm4, text=artist, relief=GROOVE, bd=2).pack(side=BOTTOM,
                                                      anchor=W,
                                                      fill=X)
    Label(fm4, text=song_title, relief=GROOVE, bd=2).pack(side=BOTTOM,
                                                          anchor=W,
                                                          fill=X)
    Label(fm4, textvariable=main.update, relief=SOLID, bd=2).pack(side=BOTTOM,
                                                                  anchor=W,
                                                                  fill=X)
    fm4.pack(side=LEFT, padx=10)
    # update string representation
    allstates()

    # draw tkinter
    main.root.mainloop()
Пример #23
0
def play_note(player, freq, beat):
    player.ChangeFrequency(freq)
    player.start(50)
    time.sleep(0.9 * beat)
    player.stop()
    time.sleep(0.1 * beat)
Пример #24
0
 def clear(self):
     self.queue = []
     self.position = -1
     player.stop()
     return self.get_queue()
Пример #25
0
	def stop(self, event):
		if player.p.loaded==True:
			if player.p.stream.is_playing==True:
				player.stop()
Пример #26
0
 def stop(self, event):
     if player.p.loaded == True:
         if player.p.stream.is_playing == True:
             player.stop()
Пример #27
0
def show_plot_and_play(np_array, frequency, np_array_orig=None):
    player.stop()
    show_plot(np_array,
              np_array_orig if np_array_orig is not None else np_array)
    root.after(500, lambda: player.play(np_array, frequency))
Пример #28
0
def runLevel(curLevel, brains, screen, maxfps, debug):
    screenSize = screen.get_size()
    
    #for darkening the screen
    darken=pygame.Surface(screen.get_size())
    darken.fill((20, 20, 30))
    darken.set_alpha(100)
    
    dark = 1
    
    #ids for timers
    bloodtimer = pygame.USEREVENT+1
    braintimer = bloodtimer + 1
    clock = pygame.time.Clock()
        
    level = terrain.Terrain(curLevel)
    world = pygame.Surface(level.background.get_size())
    osd = OSD(screenSize)

    screen.blit(level.background, (0, 0))
    pygame.display.flip()

    all, playerGroup, enviro, enemy, doors = terrain.groups(world.get_rect(), curLevel, level.tileSize)
    #enviro.draw(level.background)
    notPlayer = isogroup.ISOGroup()
    notPlayer.add(enviro, enemy)
    watchRect = pygame.rect.Rect((0,0), screenSize)
    player = playerGroup.sprites()[0]
    all.add(enviro)
    player.brains = brains

    onscreen = isogroup.ISOGroup()
    onscreenEnemy = isogroup.ISOGroup()
    
    pygame.time.set_timer(bloodtimer, player.bloodtick*maxfps)
    pygame.time.set_timer(braintimer, player.braintick*maxfps)
    
    while 1:
        clock.tick(maxfps)

        for event in pygame.event.get():
            if event.type == QUIT:
                return -1, player.brains
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return 0, player.brains
            elif event.type == KEYDOWN and event.key == K_q:
                return 0,player.brains
            elif event.type == KEYDOWN and event.key == K_F1:
                help(screen)
            elif event.type == KEYDOWN and event.key == K_UP:
                player.run('n')
            elif event.type == KEYDOWN and event.key == K_DOWN:
                player.run('s')
            elif event.type == KEYDOWN and event.key == K_LEFT:
                player.run('w')
            elif event.type == KEYDOWN and event.key == K_RIGHT:
                player.run('e')
            elif event.type == KEYDOWN and event.key == K_LCTRL:
                player.attack(enemy, osd)
            elif event.type == KEYDOWN and event.key == K_a:
                player.wounded()
            elif event.type == KEYDOWN and event.key == K_s:
                player.talk()
            elif event.type == KEYDOWN and event.key == K_d:
                enemy.sprites()[0].health = 0
            elif event.type == KEYDOWN and event.key == K_f:
                player.bite(enemy)
            elif event.type == KEYDOWN and event.key == K_LALT:
                player.morph()
            elif event.type == KEYDOWN and event.key == K_t:
                dark = not dark
            elif event.type == KEYDOWN and event.key == K_p:
                return curLevel+1, player.brains
            elif event.type == KEYUP:
                if player.action == 'walking' or player.action == 'running':
                    player.stop()
            elif event.type == bloodtimer:
                player.blood -= 1
            elif event.type == braintimer:
                player.brains -= 1

        
        onscreen.empty()
        onscreenEnemy.empty()
        for s in all.sprites():
            if s.rect.colliderect(watchRect):
                if s in enemy:
                    onscreenEnemy.add(s)
                onscreen.add(s)
                
        #print clock.get_time()/1000.0
        onscreen.update(clock.get_time()/1000.0, osd, player)

        if isogroup.spritecollideany(player, doors):
            if player.level > curLevel:
                #warp level
                return curLevel + 1, player.brains
            else:
                osd.addMessage('You are not yet powerful enough to go there.')

        if isogroup.spritecollideany(player, notPlayer):
            player.collide()
            
        for s in onscreenEnemy:
            if isogroup.spritecollideany(s, enviro) or isogroup.spritecollideany(s, playerGroup):
                s.collide()
                
        osd.update(player, clock.get_fps())
        watchRect.center = player.rect.center
        sRect = world.get_rect()
        if not sRect.contains(watchRect):
            watchRect.clamp_ip(sRect)
        
        world.blit(level.background, watchRect, watchRect)
        
        onscreen.draw(world)
        if debug:
            for thing in onscreen:
                pygame.draw.rect(world, pygame.Color('red'), thing.cRect, 1)
                pygame.draw.rect(world, pygame.Color('blue'), thing.rect, 1)
                if hasattr(thing, "attackRect"):
                    pygame.draw.rect(world, pygame.Color('green'), thing.attackRect, 1)
                if hasattr(thing, "hitRect"):
                    pygame.draw.rect(world, pygame.Color('purple'), thing.hitRect, 1)
                if hasattr(thing, "velocity"):
                    pygame.draw.line(world, (50,75,222), thing.rect.center, thing.rect.center+(thing.velocity*30), 2)
                if hasattr(thing, "wanderpoint"):
                    pygame.draw.circle(world, (120,3,85), (int(thing.wanderpoint[0]), int(thing.wanderpoint[1])), 50)
            
        screen.fill((0,0,0))
        screen.blit(world, (0, 0), watchRect)
        if (dark):
            screen.blit(darken, (0, 0))
        screen.blit(osd.osd, (0, 0))
        pygame.display.flip()
        
        if not player.alive:
            return curLevel, 0
Пример #29
0
 def stop(self):
     player.stop()
     self.updatePlayStatus()
Пример #30
0
def close_inst(audio_path):
    # stop audio and write to file on close
    stop(audio_path)
    additional_collector()
    write()
    main.root.destroy()
Пример #31
0
 def stop(self):
     """
     Stop the current playing
     """
     audioplayer.stop()
Пример #32
0
 def stop(self):
     """
     stop playing
     """
     videoplayer.stop()
Пример #33
0
 def clear(self):
     self.queue = []
     self.position = -1
     player.stop()
     return self.get_queue()
Пример #34
0
def stop_impl():
    player.stop()
    publisher.publishStatus(None)
    return jsonify({})
Пример #35
0
 def clear(self):
     session = Session()
     session.query(Packet).filter_by(player_name=PLAYER_NAME).delete()
     session.commit()
     player.stop()
     return self.get_queue()