X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=helpers%2Fmusic_file.py;h=9acdedf45026b014e39390aac7ef37a83734aa8d;hb=98ff43054fe94f333e2deda2906cd62593ded1d8;hp=667c16905859c97d997ee2fc0d54b25c22f10805;hpb=92cc4ce2e6d3372c167117c55069cad8a2e69965;p=perso%2FImmae%2FProjets%2FPython%2FMusicSampler.git diff --git a/helpers/music_file.py b/helpers/music_file.py index 667c169..9acdedf 100644 --- a/helpers/music_file.py +++ b/helpers/music_file.py @@ -1,13 +1,16 @@ import threading import pydub import pygame +import math +import time class MusicFile: - def __init__(self, filename, lock, channel_id, name = None): + def __init__(self, filename, lock, channel_id, name = None, gain = 1): self.filename = filename self.channel_id = channel_id self.name = name or filename self.raw_data = None + self.gain = gain self.loaded = False self.flag_paused = False @@ -16,7 +19,8 @@ class MusicFile: def load_sound(self, lock): lock.acquire() print("Loading « {} »".format(self.name)) - audio_segment = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100) + volume_factor = 20 * math.log10(self.gain) + audio_segment = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100).apply_gain(volume_factor) self.sound_duration = audio_segment.duration_seconds self.raw_data = audio_segment.raw_data print("Loaded « {} »".format(self.name)) @@ -29,6 +33,15 @@ class MusicFile: def is_paused(self): return self.flag_paused + @property + def sound_position(self): + if self.is_playing() and not self.is_paused(): + return min(time.time() - self.started_at, self.sound_duration) + elif self.is_playing() and self.is_paused(): + return min(self.paused_at - self.started_at, self.sound_duration) + else: + return 0 + def play(self, fade_in = 0, volume = 100, start_at = 0): self.channel().set_endevent() self.channel().set_endevent(pygame.USEREVENT) @@ -42,14 +55,17 @@ class MusicFile: else: sound = pygame.mixer.Sound(self.raw_data) + self.started_at = time.time() self.channel().play(sound, fade_ms = int(fade_in * 1000)) self.flag_paused = False def pause(self): + self.paused_at = time.time() self.channel().pause() self.flag_paused = True def unpause(self): + self.started_at += (time.time() - self.paused_at) self.channel().unpause() self.flag_paused = False