import threading import pydub import pygame class MusicFile: def __init__(self, filename, lock): self.filename = filename self.channel = None self.raw_data = None self.sound = None self.loaded = False threading.Thread(name = "MSMusicLoad", target = self.load_sound, args = [lock]).start() def load_sound(self, lock): lock.acquire() print("Loading {}".format(self.filename)) self.raw_data = pydub.AudioSegment.from_file(self.filename).raw_data self.sound = pygame.mixer.Sound(self.raw_data) print("Loaded {}".format(self.filename)) self.loaded = True lock.release() def is_playing(self): return self.channel is not None and self.channel.get_busy() def play(self, fade_in = 0, volume = 100, start_at = 0): self.set_volume(volume) if start_at > 0: song_duration = self.sound.get_length() raw_data_length = len(self.raw_data) start_offset = int((raw_data_length / song_duration) * start_at) start_offset = start_offset - (start_offset % 2) self.sound = pygame.mixer.Sound(self.raw_data[start_offset:]) else: self.sound = pygame.mixer.Sound(self.raw_data) self.channel = self.sound.play(fade_ms = fade_in * 1000) def pause(self): if self.channel is not None: self.channel.pause() def stop(self, fade_out = 0): self.channel = None if fade_out > 0: self.sound.fadeout(fade_out * 1000) else: self.sound.stop() def set_volume(self, value): if value < 0: value = 0 if value > 100: value = 100 self.sound.set_volume(value / 100) def wait_end(self): pass