Wobuzz/wobuzz/player/player.py
2024-12-24 17:22:30 +01:00

112 lines
3 KiB
Python

#!/usr/bin/python3
import os
import pygame.mixer
import pygame.event
from .track import Track
from .playlist import Playlist
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.current_playlist = Playlist(self.app)
self.playing = False
self.paused = False
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.
"""
self.current_playlist = Playlist(self.app)
self.current_playlist.load_from_paths(track_paths)
self.current_sound = self.current_playlist.current_track.sound
self.current_sound_duration = self.current_playlist.current_track.duration
def play(self):
self.music_channel.play(self.current_sound)
self.playing = True
self.paused = False
def track_finished(self):
if not self.current_playlist.on_last_track():
self.current_sound, self.current_sound_duration = self.current_playlist.next_track()
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_playlist.current_track.sound
self.current_sound_duration = self.current_playlist.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 not self.current_playlist.on_last_track():
self.music_channel.stop()
self.track_progress.stop()
self.track_finished()
def previous_track(self):
if not self.current_playlist.on_first_track():
self.music_channel.stop()
self.current_sound, self.current_sound_duration = self.current_playlist.previous_track()
self.track_progress.stop()
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_playlist.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_playlist.current_track.remaining(position)
self.play()
self.track_progress.start()