Wobuzz/wobuzz/player/player.py

115 lines
3.1 KiB
Python

#!/usr/bin/python3
import os
from PyQt6.QtCore import QTimer
import pygame.mixer
import pygame.event
from .track import Track
class Player:
def __init__(self, app, file_paths: list=[]):
self.app = app
pygame.mixer.init()
self.mixer = pygame.mixer
self.music_channel = self.mixer.Channel(0)
self.track_progress_timer = QTimer()
self.track_progress_timer.timeout.connect(self.track_finished)
self.track_progress_timer.setSingleShot(True)
self.remaining_time = 0
self.playing = False
self.paused = False
if not file_paths:
pass
# loading of last opened files will be implemented in the future
else:
self.current_playlist = self.load_tracks(file_paths)
if self.current_playlist:
self.playing_track = self.current_playlist[0]
self.current_playlist_index = 0
else:
self.playing_track = None
self.current_playlist_index = 0
def load_tracks(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))
return tracks
def track_finished(self):
self.current_playlist_index += 1
self.playing_track = self.current_playlist[self.current_playlist_index]
self.music_channel.play(self.playing_track.sound)
self.start_track_progress_timer()
self.app.gui_communication.on_track_start()
def start_playing(self):
self.music_channel.play(self.playing_track.sound)
self.start_track_progress_timer()
self.paused = False
self.playing = True
def pause(self):
self.music_channel.pause()
self.paused = True
self.pause_track_progress_timer()
def unpause(self):
self.music_channel.unpause()
self.paused = False
self.unpause_track_progress_timer()
def skip_current(self):
self.music_channel.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.music_channel.play(self.playing_track.sound)
def toggle_playing(self):
if self.playing and self.paused:
self.unpause()
elif self.playing:
self.pause()
else:
self.start_playing()
def stop(self):
self.music_channel.stop()
self.playing = False
def start_track_progress_timer(self):
self.track_progress_timer.start(self.playing_track.duration)
def pause_track_progress_timer(self):
self.remaining_time = self.track_progress_timer.remainingTime()
self.track_progress_timer.stop()
def unpause_track_progress_timer(self):
self.track_progress_timer.start(self.remaining_time)