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