4 from transitions
.extensions
import HierarchicalMachine
as Machine
6 import sounddevice
as sd
12 file_lock
= Lock("file")
14 class MusicFile(Machine
):
15 def __init__(self
, filename
, mapping
, name
= None, gain
= 1):
20 { 'name': 'loaded', 'children': ['stopped', 'playing', 'paused', 'stopping'] }
23 { 'trigger': 'load', 'source': 'initial', 'dest': 'loading'}
,
24 { 'trigger': 'fail', 'source': 'loading', 'dest': 'failed'}
,
25 { 'trigger': 'success', 'source': 'loading', 'dest': 'loaded_stopped'}
,
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'}
,
30 { 'trigger': 'stopped', 'source': 'loaded_stopping', 'dest': 'loaded_stopped'}
33 Machine
.__init
__(self
, states
=states
, transitions
=transitions
, initial
='initial')
36 self
.mapping
= mapping
37 self
.filename
= filename
39 self
.name
= name
or filename
40 self
.audio_segment
= None
41 self
.audio_segment_frame_width
= 0
42 self
.volume_factor
= gain
43 self
.music_lock
= Lock("music__" + filename
)
44 self
.wait_event
= threading
.Event()
46 threading
.Thread(name
= "MSMusicLoad", target
= self
.load
).start()
48 def on_enter_loading(self
):
51 print("Loading « {} »".format(self
.name
))
52 db_gain
= gain(self
.volume_factor
* 100)
53 self
.audio_segment
= pydub
.AudioSegment
.from_file(self
.filename
).set_frame_rate(44100).apply_gain(db_gain
)
54 self
.audio_segment_frame_width
= self
.audio_segment
.frame_width
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
62 print("Loaded « {} »".format(self
.name
))
64 def check_is_loaded(self
):
65 return self
.state
.startswith('loaded_')
67 def is_not_stopped(self
):
68 return self
.check_is_loaded() and not self
.is_loaded_stopped()
71 return self
.is_loaded_paused()
74 def sound_position(self
):
75 if self
.is_not_stopped():
76 return self
.current_frame
/ self
.current_audio_segment
.frame_rate
80 def play(self
, fade_in
= 0, volume
= 100, loop
= 0, start_at
= 0):
81 db_gain
= gain(volume
) + self
.mapping
.master_gain
85 ms
= int(start_at
* 1000)
86 ms_fi
= int(fade_in
* 1000)
88 self
.current_audio_segment
= (self
.audio_segment
+ db_gain
)
89 self
.current_frame
= int(start_at
* self
.audio_segment
.frame_rate
)
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
95 self
.a_s_with_effect
= None
97 self
.before_loaded_playing()
100 def before_loaded_playing(self
):
101 with self
.music_lock
:
102 segment
= self
.current_audio_segment
104 self
.stream
= sd
.RawOutputStream(samplerate
=segment
.frame_rate
,
105 channels
=segment
.channels
,
106 dtype
='int' + str(8*segment
.sample_width
), # FIXME: ?
108 callback
=self
.play_callback
,
109 finished_callback
=self
.finished_callback
112 def on_enter_loaded_playing(self
):
115 def on_enter_loaded_paused(self
):
118 def finished_callback(self
):
119 if self
.is_loaded_playing():
121 if self
.is_loaded_stopping():
124 def on_enter_loaded_stopped(self
):
125 self
.wait_event
.set()
127 def play_callback(self
, out_data
, frame_count
, time_info
, status_flags
):
128 with self
.music_lock
:
129 [data
, nb_frames
] = self
.get_next_sample(frame_count
)
130 if nb_frames
< frame_count
:
131 if self
.is_loaded_playing() and self
.loop
!= 0:
133 self
.current_frame
= 0
134 [new_data
, new_nb_frames
] = self
.get_next_sample(frame_count
- nb_frames
)
136 nb_frames
+= new_nb_frames
138 raise sd
.CallbackStop
140 out_data
[:] = data
.ljust(len(out_data
), b
'\0')
142 def get_next_sample(self
, frame_count
):
143 fw
= self
.audio_segment_frame_width
147 if self
.a_s_with_effect
is not None:
148 segment
= self
.a_s_with_effect
149 max_val
= int(segment
.frame_count())
151 start_i
= max(self
.current_frame_with_effect
, 0)
152 end_i
= min(self
.current_frame_with_effect
+ frame_count
, max_val
)
154 data
+= segment
._data
[(start_i
* fw
):(end_i
* fw
)]
156 frame_count
= max(0, self
.current_frame_with_effect
+ frame_count
- max_val
)
158 self
.current_frame_with_effect
+= end_i
- start_i
159 self
.current_frame
+= end_i
- start_i
160 nb_frames
+= end_i
- start_i
163 self
.a_s_with_effect
= None
165 segment
= self
.current_audio_segment
166 max_val
= int(segment
.frame_count())
168 start_i
= max(self
.current_frame
, 0)
169 end_i
= min(self
.current_frame
+ frame_count
, max_val
)
170 data
+= segment
._data
[(start_i
* fw
):(end_i
* fw
)]
171 nb_frames
+= end_i
- start_i
172 self
.current_frame
+= end_i
- start_i
174 return [data
, nb_frames
]
176 def seek(self
, value
= 0, delta
= False):
177 # We don't want to do that while stopping
178 if not (self
.is_loaded_playing() or self
.is_loaded_paused()):
180 with self
.music_lock
:
181 self
.a_s_with_effect
= None
182 self
.current_frame
= max(0, int(delta
) * self
.current_frame
+ int(value
* self
.audio_segment
.frame_rate
))
183 # FIXME: si on fait un seek + delta, adapter le "loop"
185 def stop(self
, fade_out
= 0, wait
= False):
186 if self
.is_loaded_playing():
187 ms
= int(self
.sound_position
* 1000)
188 ms_fo
= max(1, int(fade_out
* 1000))
190 # FIXME: stop fade_out puis seek -5 -> on abandonne le fade ? (cf
191 # commentaire dans fonction seek
192 with self
.music_lock
:
193 self
.current_audio_segment
= self
.current_audio_segment
[:ms
+ ms_fo
].fade_out(ms_fo
)
201 def set_gain(self
, db_gain
):
202 if not self
.is_not_stopped():
205 new_audio_segment
= self
.current_audio_segment
+ db_gain
207 new_a_s_with_effect
= None
208 if self
.a_s_with_effect
is not None:
209 new_a_s_with_effect
= self
.a_s_with_effect
+ db_gain
211 with self
.music_lock
:
212 self
.current_audio_segment
= new_audio_segment
213 self
.a_s_with_effect
= new_a_s_with_effect
215 def set_volume(self
, value
, delta
= False):
216 [db_gain
, self
.volume
] = gain(value
+ int(delta
) * self
.volume
, self
.volume
)
218 self
.set_gain(db_gain
)
221 self
.wait_event
.clear()
222 self
.wait_event
.wait()
224 # Add some more functions to AudioSegments
225 def get_sample_slice_data(self
, start_sample
=0, end_sample
=float('inf')):
226 max_val
= int(self
.frame_count())
228 start_i
= max(start_sample
, 0) * self
.frame_width
229 end_i
= min(end_sample
, max_val
) * self
.frame_width
231 return self
._data
[start_i
:end_i
]
233 pydub
.AudioSegment
.get_sample_slice_data
= get_sample_slice_data