#!/usr/bin/python3 import os import pygame.mixer import pygame.event from .track import Track from .track_progress_timer import TrackProgress from .play_state import PlayState class Player: def __init__(self, app): self.app = app self.track_progress = TrackProgress(self.app) self.play_state = PlayState() pygame.mixer.init() self.mixer = pygame.mixer self.music_channel = self.mixer.Channel(0) self.current_playlist = [] self.playing_track = None self.current_playlist_index = 0 self.playing_segment = None self.playing_segment_duration = 0 def load_tracks_from_paths(self, track_paths: list[str]): """ Load tracks from list of paths. """ tracks = [] for track_path in track_paths: if os.path.isfile(track_path): tracks.append(Track(track_path, True)) self.current_playlist = tracks self.playing_track = self.current_playlist[0] self.current_playlist_index = 0 self.playing_segment = self.playing_track.sound self.playing_segment_duration = self.playing_track.duration def track_finished(self): self.current_playlist_index += 1 if self.current_playlist_index < len(self.current_playlist): self.playing_track = self.current_playlist[self.current_playlist_index] self.playing_segment = self.playing_track.sound self.playing_segment_duration = self.playing_track.duration self.music_channel.play(self.playing_track.sound) self.track_progress.start() self.app.gui_communication.on_track_start() else: self.current_playlist_index -= 1 self.stop() def start_playing(self): self.music_channel.play(self.playing_track.sound) self.track_progress.start() self.play_state.paused = False self.play_state.playing = True def pause(self): self.music_channel.pause() self.track_progress.pause() self.play_state.paused = True def unpause(self): self.music_channel.unpause() self.track_progress.unpause() self.play_state.paused = False def skip_current(self): self.music_channel.stop() self.track_progress.stop() self.track_finished() def previous_track(self): if self.current_playlist_index > 0: self.music_channel.stop() self.current_playlist_index -= 1 self.playing_track = self.current_playlist[self.current_playlist_index] self.track_progress.stop() self.playing_segment = self.playing_track.sound self.playing_segment_duration = self.playing_track.duration self.music_channel.play(self.playing_track.sound) self.track_progress.start() self.app.gui_communication.on_track_start() def toggle_playing(self): if self.play_state.playing and self.play_state.paused: self.unpause() elif self.play_state.playing: self.pause() else: self.start_playing() def stop(self): self.music_channel.stop() self.track_progress.stop() self.play_state.playing = False self.playing_segment_duration = self.playing_track.duration def seek(self, position: int): self.play_state.searched = True self.music_channel.stop() self.track_progress.stop() (self.playing_segment, self.playing_segment_duration) = self.playing_track.remaining(position) self.music_channel.play(self.playing_segment) self.track_progress.start()