#!/usr/bin/python3 import os import pygame.mixer import pygame.event from .track import Track from .track_progress_timer import TrackProgress class Player: def __init__(self, app): self.app = app pygame.mixer.init() self.mixer = pygame.mixer self.music_channel = self.mixer.Channel(0) self.track_progress = TrackProgress(self.app) self.playing = False self.paused = False self.current_playlist = [] self.current_playlist_index = 0 self.current_track = None self.current_sound = None self.current_sound_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.current_playlist_index = 0 self.current_track = self.current_playlist[0] self.current_sound = self.current_track.sound self.current_sound_duration = self.current_track.duration def play(self): self.music_channel.play(self.current_sound) self.playing = True self.paused = False def track_finished(self): # if the last track wasn't the last in the playlist if self.current_playlist_index < len(self.current_playlist) - 1: self.current_playlist_index += 1 self.current_track = self.current_playlist[self.current_playlist_index] self.current_sound = self.current_track.sound self.current_sound_duration = self.current_track.duration self.play() self.track_progress.start() self.app.gui_communication.on_track_start() else: self.stop() def start_playing(self): self.current_sound = self.current_track.sound self.current_sound_duration = self.current_track.duration self.play() self.track_progress.start() def pause(self): self.music_channel.pause() self.track_progress.pause() self.paused = True def unpause(self): self.music_channel.unpause() self.track_progress.unpause() self.playing = True self.paused = False def next_track(self): if self.current_playlist_index < len(self.current_playlist) - 1: # if the playing track isn't the last self.music_channel.stop() self.track_progress.stop() self.track_finished() def previous_track(self): if self.current_playlist_index > 0: # if the current track isn't the first in the playlist self.music_channel.stop() self.current_playlist_index -= 1 self.current_track = self.current_playlist[self.current_playlist_index] self.track_progress.stop() self.current_sound = self.current_track.sound self.current_sound_duration = self.current_track.duration self.play() self.track_progress.start() self.app.gui_communication.on_track_start() def stop(self): self.music_channel.stop() self.track_progress.stop() self.current_sound_duration = self.current_track.duration self.playing = False self.paused = False def seek(self, position: int): self.music_channel.stop() self.track_progress.stop() (self.current_sound, self.current_sound_duration) = self.current_track.remaining(position) self.play() self.track_progress.start()