]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - helpers/music_file.py
Move from pygame to sounddevice for sound handling
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / music_file.py
1 import threading
2 import pydub
3 import math
4 import time
5 from transitions.extensions import HierarchicalMachine as Machine
6
7 import pyaudio as pa
8 import sounddevice as sd
9 import os.path
10
11 from .lock import Lock
12 file_lock = Lock("file")
13
14 pyaudio = pa.PyAudio()
15
16 class MusicFile(Machine):
17 def __init__(self, filename, name = None, gain = 1):
18 states = [
19 'initial',
20 'loading',
21 'failed',
22 { 'name': 'loaded', 'children': ['stopped', 'playing', 'paused', 'stopping'] }
23 ]
24 transitions = [
25 { 'trigger': 'load', 'source': 'initial', 'dest': 'loading'},
26 { 'trigger': 'fail', 'source': 'loading', 'dest': 'failed'},
27 { 'trigger': 'success', 'source': 'loading', 'dest': 'loaded_stopped'},
28 { 'trigger': 'start_playing', 'source': 'loaded_stopped', 'dest': 'loaded_playing'},
29 { 'trigger': 'pause', 'source': 'loaded_playing', 'dest': 'loaded_paused'},
30 { 'trigger': 'unpause', 'source': 'loaded_paused', 'dest': 'loaded_playing'},
31 { 'trigger': 'stop_playing', 'source': ['loaded_playing','loaded_paused'], 'dest': 'loaded_stopping'},
32 { 'trigger': 'stopped', 'source': 'loaded_stopping', 'dest': 'loaded_stopped'}
33 ]
34
35 Machine.__init__(self, states=states, transitions=transitions, initial='initial')
36
37 self.filename = filename
38 self.stream = None
39 self.name = name or filename
40 self.audio_segment = None
41 self.gain = gain
42 self.music_lock = Lock("music__" + filename)
43
44 self.flag_paused = False
45 threading.Thread(name = "MSMusicLoad", target = self.load).start()
46
47 def on_enter_loading(self):
48 with file_lock:
49 try:
50 print("Loading « {} »".format(self.name))
51 volume_factor = 20 * math.log10(self.gain)
52 self.audio_segment = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100).apply_gain(volume_factor)
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))
61
62 def check_is_loaded(self):
63 return self.state.startswith('loaded_')
64
65 def is_not_stopped(self):
66 return self.check_is_loaded() and not self.is_loaded_stopped()
67
68 def is_paused(self):
69 return self.is_loaded_paused()
70
71 @property
72 def sound_position(self):
73 if self.is_not_stopped():
74 return self.current_frame / self.current_audio_segment.frame_rate
75 else:
76 return 0
77
78 def play(self, fade_in = 0, volume = 100, start_at = 0):
79 self.db_gain = self.volume_to_gain(volume)
80 ms = int(start_at * 1000)
81 ms_fi = max(1, int(fade_in * 1000))
82 with self.music_lock:
83 self.current_audio_segment = (self.audio_segment + self.db_gain).fade(from_gain=-120, duration=ms_fi, start=ms)
84 self.before_loaded_playing(initial_frame = int(start_at * self.audio_segment.frame_rate))
85 self.start_playing()
86
87 def before_loaded_playing(self, initial_frame = 0):
88 self.current_frame = initial_frame
89 with self.music_lock:
90 segment = self.current_audio_segment
91
92 self.stream = sd.RawOutputStream(samplerate=segment.frame_rate,
93 channels=segment.channels,
94 dtype='int' + str(8*segment.sample_width), # FIXME: ?
95 latency=1.,
96 callback=self.play_callback,
97 finished_callback=self.finished_callback
98 )
99
100 def on_enter_loaded_playing(self):
101 self.stream.start()
102
103 def on_enter_loaded_paused(self):
104 self.stream.stop()
105
106 def finished_callback(self):
107 if self.is_loaded_playing():
108 self.stop_playing()
109 if self.is_loaded_stopping():
110 self.stopped()
111
112 def play_callback(self, out_data, frame_count, time_info, status_flags):
113 with self.music_lock:
114 audio_segment = self.current_audio_segment.get_sample_slice_data(
115 start_sample=self.current_frame,
116 end_sample=self.current_frame + frame_count
117 )
118 self.current_frame += frame_count
119 if len(audio_segment) == 0:
120 raise sd.CallbackStop
121
122 out_data[:] = audio_segment.ljust(len(out_data), b'\0')
123
124 def stop(self, fade_out = 0):
125 if self.is_loaded_playing():
126 ms = int(self.sound_position * 1000)
127 ms_fo = max(1, int(fade_out * 1000))
128
129 with self.music_lock:
130 self.current_audio_segment = self.current_audio_segment[:ms + ms_fo].fade_out(ms_fo)
131 self.stop_playing()
132 else:
133 self.stop_playing()
134 self.stopped()
135
136 def set_volume(self, value):
137 if self.is_loaded_stopped():
138 return
139
140 db_gain = self.volume_to_gain(value)
141 new_audio_segment = self.current_audio_segment + (db_gain - self.db_gain)
142 self.db_gain = db_gain
143 with self.music_lock:
144 self.current_audio_segment = new_audio_segment
145
146 def volume_to_gain(self, volume):
147 return 20 * math.log10(max(volume, 0.0001) / 100)
148
149 def wait_end(self):
150 # FIXME: todo
151 pass
152
153 # Add some more functions to AudioSegments
154 def get_sample_slice_data(self, start_sample=0, end_sample=float('inf')):
155 max_val = int(self.frame_count())
156
157 start_i = max(start_sample, 0) * self.frame_width
158 end_i = min(end_sample, max_val) * self.frame_width
159
160 return self._data[start_i:end_i]
161
162 pydub.AudioSegment.get_sample_slice_data = get_sample_slice_data