]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blobdiff - helpers/music_file.py
Apply initial gain to music file
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
index 10784596a38db66cbde3594aab0adcac3b2231fb..892519d2e843be9423b98399aad37de6ce7060f4 100644 (file)
@@ -1,13 +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.gain = gain
 
         self.loaded = False
         self.flag_paused = False
@@ -16,7 +18,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))
@@ -42,7 +45,7 @@ class MusicFile:
         else:
             sound = pygame.mixer.Sound(self.raw_data)
 
-        self.channel().play(sound, fade_ms = fade_in * 1000)
+        self.channel().play(sound, fade_ms = int(fade_in * 1000))
         self.flag_paused = False
 
     def pause(self):
@@ -55,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()