]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - helpers/music_file.py
Apply initial gain to music file
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
1 import threading
2 import pydub
3 import pygame
4 import math
5
6 class MusicFile:
7 def __init__(self, filename, lock, channel_id, name = None, gain = 1):
8 self.filename = filename
9 self.channel_id = channel_id
10 self.name = name or filename
11 self.raw_data = None
12 self.gain = gain
13
14 self.loaded = False
15 self.flag_paused = False
16 threading.Thread(name = "MSMusicLoad", target = self.load_sound, args = [lock]).start()
17
18 def load_sound(self, lock):
19 lock.acquire()
20 print("Loading « {} »".format(self.name))
21 volume_factor = 20 * math.log10(self.gain)
22 audio_segment = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100).apply_gain(volume_factor)
23 self.sound_duration = audio_segment.duration_seconds
24 self.raw_data = audio_segment.raw_data
25 print("Loaded « {} »".format(self.name))
26 self.loaded = True
27 lock.release()
28
29 def is_playing(self):
30 return self.channel().get_busy()
31
32 def is_paused(self):
33 return self.flag_paused
34
35 def play(self, fade_in = 0, volume = 100, start_at = 0):
36 self.channel().set_endevent()
37 self.channel().set_endevent(pygame.USEREVENT)
38 self.set_volume(volume)
39
40 if start_at > 0:
41 raw_data_length = len(self.raw_data)
42 start_offset = int((raw_data_length / self.sound_duration) * start_at)
43 start_offset = start_offset - (start_offset % 2)
44 sound = pygame.mixer.Sound(self.raw_data[start_offset:])
45 else:
46 sound = pygame.mixer.Sound(self.raw_data)
47
48 self.channel().play(sound, fade_ms = int(fade_in * 1000))
49 self.flag_paused = False
50
51 def pause(self):
52 self.channel().pause()
53 self.flag_paused = True
54
55 def unpause(self):
56 self.channel().unpause()
57 self.flag_paused = False
58
59 def stop(self, fade_out = 0):
60 if fade_out > 0:
61 self.channel().fadeout(int(fade_out * 1000))
62 else:
63 self.channel().stop()
64
65 def set_volume(self, value):
66 if value < 0:
67 value = 0
68 if value > 100:
69 value = 100
70 self.channel().set_volume(value / 100)
71
72 def wait_end(self):
73 pass
74
75 def channel(self):
76 return pygame.mixer.Channel(self.channel_id)