]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blame - helpers/music_file.py
Add a common mixer
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
CommitLineData
be27763f
IB
1import threading
2import pydub
98ff4305 3import time
60979de4 4from transitions.extensions import HierarchicalMachine as Machine
be27763f 5
29597680
IB
6import os.path
7
8from .lock import Lock
1b4b78f5
IB
9from . import gain
10
29597680
IB
11file_lock = Lock("file")
12
60979de4 13class MusicFile(Machine):
1b4b78f5 14 def __init__(self, filename, mapping, name = None, gain = 1):
60979de4
IB
15 states = [
16 'initial',
17 'loading',
18 'failed',
29597680 19 { 'name': 'loaded', 'children': ['stopped', 'playing', 'paused', 'stopping'] }
60979de4
IB
20 ]
21 transitions = [
22 { 'trigger': 'load', 'source': 'initial', 'dest': 'loading'},
23 { 'trigger': 'fail', 'source': 'loading', 'dest': 'failed'},
24 { 'trigger': 'success', 'source': 'loading', 'dest': 'loaded_stopped'},
29597680
IB
25 { 'trigger': 'start_playing', 'source': 'loaded_stopped', 'dest': 'loaded_playing'},
26 { 'trigger': 'pause', 'source': 'loaded_playing', 'dest': 'loaded_paused'},
27 { 'trigger': 'unpause', 'source': 'loaded_paused', 'dest': 'loaded_playing'},
28 { 'trigger': 'stop_playing', 'source': ['loaded_playing','loaded_paused'], 'dest': 'loaded_stopping'},
22514f3a 29 { 'trigger': 'stopped', 'source': 'loaded_stopping', 'dest': 'loaded_stopped', 'after': 'trigger_stopped_events'}
60979de4
IB
30 ]
31
32 Machine.__init__(self, states=states, transitions=transitions, initial='initial')
33
1b4b78f5
IB
34 self.volume = 100
35 self.mapping = mapping
be27763f 36 self.filename = filename
9de92b6d 37 self.name = name or filename
29597680 38 self.audio_segment = None
ccc8b4f2 39 self.audio_segment_frame_width = 0
1b4b78f5 40 self.volume_factor = gain
29597680 41 self.music_lock = Lock("music__" + filename)
0deb82a5 42 self.wait_event = threading.Event()
be27763f 43
29597680
IB
44 threading.Thread(name = "MSMusicLoad", target = self.load).start()
45
46 def on_enter_loading(self):
47 with file_lock:
48 try:
49 print("Loading « {} »".format(self.name))
1b4b78f5 50 db_gain = gain(self.volume_factor * 100)
22514f3a 51 self.audio_segment = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100).set_channels(2).set_sample_width(2).apply_gain(db_gain)
ccc8b4f2 52 self.audio_segment_frame_width = self.audio_segment.frame_width
29597680
IB
53 self.sound_duration = self.audio_segment.duration_seconds
54 except Exception as e:
55 print("failed to load « {} »: {}".format(self.name, e))
56 self.loading_error = e
57 self.fail()
58 else:
59 self.success()
60 print("Loaded « {} »".format(self.name))
60979de4
IB
61
62 def check_is_loaded(self):
63 return self.state.startswith('loaded_')
be27763f 64
29597680
IB
65 def is_not_stopped(self):
66 return self.check_is_loaded() and not self.is_loaded_stopped()
0e5d59f7 67
9de92b6d 68 def is_paused(self):
29597680 69 return self.is_loaded_paused()
9de92b6d 70
98ff4305
IB
71 @property
72 def sound_position(self):
29597680
IB
73 if self.is_not_stopped():
74 return self.current_frame / self.current_audio_segment.frame_rate
98ff4305
IB
75 else:
76 return 0
77
6f4944c1 78 def play(self, fade_in = 0, volume = 100, loop = 0, start_at = 0):
1b4b78f5
IB
79 db_gain = gain(volume) + self.mapping.master_gain
80 self.volume = volume
6f4944c1 81 self.loop = loop
1b4b78f5 82
29597680 83 ms = int(start_at * 1000)
ccc8b4f2 84 ms_fi = int(fade_in * 1000)
29597680 85 with self.music_lock:
ccc8b4f2
IB
86 self.current_audio_segment = (self.audio_segment + db_gain)
87 self.current_frame = int(start_at * self.audio_segment.frame_rate)
88 if ms_fi > 0:
89 # FIXME: apply it to repeated when looping?
90 self.a_s_with_effect = self.current_audio_segment[ms:ms+ms_fi].fade_in(ms_fi)
91 self.current_frame_with_effect = 0
92 else:
93 self.a_s_with_effect = None
94
29597680
IB
95 self.start_playing()
96
29597680 97 def on_enter_loaded_playing(self):
22514f3a 98 self.mapping.mixer.add_file(self)
29597680
IB
99
100 def finished_callback(self):
101 if self.is_loaded_playing():
102 self.stop_playing()
103 if self.is_loaded_stopping():
104 self.stopped()
105
22514f3a
IB
106 def trigger_stopped_events(self):
107 self.mapping.mixer.remove_file(self)
0deb82a5
IB
108 self.wait_event.set()
109
22514f3a
IB
110 def play_callback(self, out_data_length, frame_count):
111 if self.is_loaded_paused():
112 return b'\0' * out_data_length
113
29597680 114 with self.music_lock:
ccc8b4f2
IB
115 [data, nb_frames] = self.get_next_sample(frame_count)
116 if nb_frames < frame_count:
6f4944c1
IB
117 if self.is_loaded_playing() and self.loop != 0:
118 self.loop -= 1
ccc8b4f2
IB
119 self.current_frame = 0
120 [new_data, new_nb_frames] = self.get_next_sample(frame_count - nb_frames)
121 data += new_data
122 nb_frames += new_nb_frames
123 elif nb_frames == 0:
22514f3a 124 threading.Thread(name = "MSFinishedCallback", target=self.finished_callback).start()
29597680 125
22514f3a 126 return data.ljust(out_data_length, b'\0')
ccc8b4f2
IB
127
128 def get_next_sample(self, frame_count):
129 fw = self.audio_segment_frame_width
130
131 data = b""
132 nb_frames = 0
133 if self.a_s_with_effect is not None:
134 segment = self.a_s_with_effect
135 max_val = int(segment.frame_count())
136
137 start_i = max(self.current_frame_with_effect, 0)
138 end_i = min(self.current_frame_with_effect + frame_count, max_val)
139
140 data += segment._data[(start_i * fw):(end_i * fw)]
141
142 frame_count = max(0, self.current_frame_with_effect + frame_count - max_val)
143
144 self.current_frame_with_effect += end_i - start_i
145 self.current_frame += end_i - start_i
146 nb_frames += end_i - start_i
147
148 if frame_count > 0:
149 self.a_s_with_effect = None
150
151 segment = self.current_audio_segment
152 max_val = int(segment.frame_count())
153
154 start_i = max(self.current_frame, 0)
155 end_i = min(self.current_frame + frame_count, max_val)
156 data += segment._data[(start_i * fw):(end_i * fw)]
157 nb_frames += end_i - start_i
158 self.current_frame += end_i - start_i
159
160 return [data, nb_frames]
be27763f 161
52d58baf
IB
162 def seek(self, value = 0, delta = False):
163 # We don't want to do that while stopping
164 if not (self.is_loaded_playing() or self.is_loaded_paused()):
165 return
166 with self.music_lock:
ccc8b4f2 167 self.a_s_with_effect = None
52d58baf 168 self.current_frame = max(0, int(delta) * self.current_frame + int(value * self.audio_segment.frame_rate))
ccc8b4f2 169 # FIXME: si on fait un seek + delta, adapter le "loop"
52d58baf 170
1b4b78f5 171 def stop(self, fade_out = 0, wait = False):
29597680
IB
172 if self.is_loaded_playing():
173 ms = int(self.sound_position * 1000)
174 ms_fo = max(1, int(fade_out * 1000))
175
ccc8b4f2
IB
176 # FIXME: stop fade_out puis seek -5 -> on abandonne le fade ? (cf
177 # commentaire dans fonction seek
22514f3a 178 new_audio_segment = self.current_audio_segment[:ms + ms_fo].fade_out(ms_fo)
29597680 179 with self.music_lock:
22514f3a
IB
180 self.current_audio_segment = new_audio_segment
181 self.stop_playing()
1b4b78f5
IB
182 if wait:
183 self.wait_end()
0e5d59f7 184 else:
29597680
IB
185 self.stop_playing()
186 self.stopped()
0e5d59f7 187
1b4b78f5
IB
188 def set_gain(self, db_gain):
189 if not self.is_not_stopped():
29597680
IB
190 return
191
1b4b78f5
IB
192 new_audio_segment = self.current_audio_segment + db_gain
193
ccc8b4f2
IB
194 new_a_s_with_effect = None
195 if self.a_s_with_effect is not None:
196 new_a_s_with_effect = self.a_s_with_effect + db_gain
197
29597680
IB
198 with self.music_lock:
199 self.current_audio_segment = new_audio_segment
ccc8b4f2 200 self.a_s_with_effect = new_a_s_with_effect
29597680 201
8e50011c
IB
202 def set_volume(self, value, delta = False):
203 [db_gain, self.volume] = gain(value + int(delta) * self.volume, self.volume)
1b4b78f5
IB
204
205 self.set_gain(db_gain)
be27763f 206
b86db9f1 207 def wait_end(self):
0deb82a5
IB
208 self.wait_event.clear()
209 self.wait_event.wait()
d479af33 210
29597680
IB
211# Add some more functions to AudioSegments
212def get_sample_slice_data(self, start_sample=0, end_sample=float('inf')):
213 max_val = int(self.frame_count())
214
215 start_i = max(start_sample, 0) * self.frame_width
216 end_i = min(end_sample, max_val) * self.frame_width
217
218 return self._data[start_i:end_i]
219
220pydub.AudioSegment.get_sample_slice_data = get_sample_slice_data