X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=helpers%2Fmusic_file.py;h=892519d2e843be9423b98399aad37de6ce7060f4;hb=87f211fb622ef640249628b65d0bc8daca889f2c;hp=cdc9836c19a299b82b2ba2fcca17495ea5f53cd9;hpb=425dd061bf64a8304ec96aec870b0e2e24fa44f4;p=perso%2FImmae%2FProjets%2FPython%2FMusicSampler.git diff --git a/helpers/music_file.py b/helpers/music_file.py index cdc9836..892519d 100644 --- a/helpers/music_file.py +++ b/helpers/music_file.py @@ -1,14 +1,15 @@ import threading import pydub import pygame +import math 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.sound = None + self.gain = gain self.loaded = False self.flag_paused = False @@ -17,8 +18,10 @@ class MusicFile: def load_sound(self, lock): lock.acquire() print("Loading « {} »".format(self.name)) - self.raw_data = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100).raw_data - self.sound = pygame.mixer.Sound(self.raw_data) + 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)) self.loaded = True lock.release() @@ -35,15 +38,14 @@ class MusicFile: 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 = int((raw_data_length / self.sound_duration) * start_at) start_offset = start_offset - (start_offset % 2) - self.sound = pygame.mixer.Sound(self.raw_data[start_offset:]) + sound = pygame.mixer.Sound(self.raw_data[start_offset:]) else: - self.sound = pygame.mixer.Sound(self.raw_data) + sound = pygame.mixer.Sound(self.raw_data) - self.channel().play(self.sound, fade_ms = fade_in * 1000) + self.channel().play(sound, fade_ms = int(fade_in * 1000)) self.flag_paused = False def pause(self): @@ -56,7 +58,7 @@ class MusicFile: def stop(self, fade_out = 0): if fade_out > 0: - self.channel().fadeout(fade_out * 1000) + self.channel().fadeout(int(fade_out * 1000)) else: self.channel().stop() @@ -65,7 +67,7 @@ class MusicFile: value = 0 if value > 100: value = 100 - self.sound.set_volume(value / 100) + self.channel().set_volume(value / 100) def wait_end(self): pass