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