]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blobdiff - helpers/music_file.py
Fix channels and description with blank lines
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
index 39b0566ccd5c68ae925af87d93c45cb630f2dc78..f6b0117d1f1bf71f67d6d9973c1e9b80b7ecf226 100644 (file)
@@ -3,14 +3,14 @@ import pydub
 import pygame
 
 class MusicFile:
-    def __init__(self, filename, lock):
+    def __init__(self, filename, lock, channel_id):
         self.filename = filename
-        self.channel = None
+        self.channel_id = channel_id
         self.raw_data = None
         self.sound = None
 
         self.loaded = False
-        threading.Thread(target = self.load_sound, args = [lock]).start()
+        threading.Thread(name = "MSMusicLoad", target = self.load_sound, args = [lock]).start()
 
     def load_sound(self, lock):
         lock.acquire()
@@ -21,15 +21,41 @@ class MusicFile:
         self.loaded = True
         lock.release()
 
-    def play(self):
-        self.channel = self.sound.play()
+    def is_playing(self):
+        return self.channel().get_busy()
 
-    def pause(self):
-        if self.channel is not None:
-            self.channel.pause()
+    def play(self, fade_in = 0, volume = 100, start_at = 0):
+        self.set_volume(volume)
 
-    def stop(self):
-        self.channel = None
-        self.sound.stop()
+        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().play(self.sound, fade_ms = fade_in * 1000)
 
+    def pause(self):
+        self.channel().pause()
+
+    def stop(self, fade_out = 0):
+        if fade_out > 0:
+            self.channel().fadeout(fade_out * 1000)
+        else:
+            self.channel().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
+
+    def channel(self):
+        return pygame.mixer.Channel(self.channel_id)