aboutsummaryrefslogtreecommitdiff
path: root/helpers/music_file.py
blob: 0bfb1eca8e2d29b1b84c3ef7ae693ff8d05826ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import threading
import pydub
import time
from transitions.extensions import HierarchicalMachine as Machine

import pyaudio as pa
import sounddevice as sd
import os.path

from .lock import Lock
from . import gain

file_lock = Lock("file")

pyaudio = pa.PyAudio()

class MusicFile(Machine):
    def __init__(self, filename, mapping, name = None, gain = 1):
        states = [
            'initial',
            'loading',
            'failed',
            { 'name': 'loaded', 'children': ['stopped', 'playing', 'paused', 'stopping'] }
        ]
        transitions = [
            { 'trigger': 'load', 'source':  'initial', 'dest': 'loading'},
            { 'trigger': 'fail', 'source':  'loading', 'dest': 'failed'},
            { 'trigger': 'success', 'source':  'loading', 'dest': 'loaded_stopped'},
            { 'trigger': 'start_playing', 'source':  'loaded_stopped', 'dest': 'loaded_playing'},
            { 'trigger': 'pause', 'source':  'loaded_playing', 'dest': 'loaded_paused'},
            { 'trigger': 'unpause', 'source':  'loaded_paused', 'dest': 'loaded_playing'},
            { 'trigger': 'stop_playing', 'source': ['loaded_playing','loaded_paused'], 'dest': 'loaded_stopping'},
            { 'trigger': 'stopped', 'source':  'loaded_stopping', 'dest': 'loaded_stopped'}
        ]

        Machine.__init__(self, states=states, transitions=transitions, initial='initial')

        self.volume = 100
        self.mapping = mapping
        self.filename = filename
        self.stream = None
        self.name = name or filename
        self.audio_segment = None
        self.volume_factor = gain
        self.music_lock = Lock("music__" + filename)
        self.wait_event = threading.Event()

        threading.Thread(name = "MSMusicLoad", target = self.load).start()

    def on_enter_loading(self):
        with file_lock:
            try:
                print("Loading « {} »".format(self.name))
                db_gain = gain(self.volume_factor * 100)
                self.audio_segment = pydub.AudioSegment.from_file(self.filename).set_frame_rate(44100).apply_gain(db_gain)
                self.sound_duration = self.audio_segment.duration_seconds
            except Exception as e:
                print("failed to load « {} »: {}".format(self.name, e))
                self.loading_error = e
                self.fail()
            else:
                self.success()
                print("Loaded « {} »".format(self.name))

    def check_is_loaded(self):
        return self.state.startswith('loaded_')

    def is_not_stopped(self):
        return self.check_is_loaded() and not self.is_loaded_stopped()

    def is_paused(self):
        return self.is_loaded_paused()

    @property
    def sound_position(self):
        if self.is_not_stopped():
            return self.current_frame / self.current_audio_segment.frame_rate
        else:
            return 0

    def play(self, fade_in = 0, volume = 100, loop = 0, start_at = 0):
        db_gain = gain(volume) + self.mapping.master_gain
        self.volume = volume
        self.loop = loop

        ms = int(start_at * 1000)
        ms_fi = max(1, int(fade_in * 1000))
        with self.music_lock:
            self.current_audio_segment = (self.audio_segment + db_gain).fade(from_gain=-120, duration=ms_fi, start=ms)
        self.initial_frame = int(start_at * self.audio_segment.frame_rate)
        self.before_loaded_playing()
        self.start_playing()

    def before_loaded_playing(self):
        self.current_frame = self.initial_frame
        with self.music_lock:
            segment = self.current_audio_segment

            self.stream = sd.RawOutputStream(samplerate=segment.frame_rate,
                            channels=segment.channels,
                            dtype='int' + str(8*segment.sample_width), # FIXME: ?
                            latency=1.,
                            callback=self.play_callback,
                            finished_callback=self.finished_callback
                            )

    def on_enter_loaded_playing(self):
        self.stream.start()

    def on_enter_loaded_paused(self):
        self.stream.stop()

    def finished_callback(self):
        if self.is_loaded_playing():
            self.stop_playing()
        if self.is_loaded_stopping():
            self.stopped()

    def on_enter_loaded_stopped(self):
        self.wait_event.set()

    def play_callback(self, out_data, frame_count, time_info, status_flags):
        with self.music_lock:
            audio_segment = self.current_audio_segment.get_sample_slice_data(
                                start_sample=self.current_frame,
                                end_sample=self.current_frame + frame_count
                                )
            self.current_frame += frame_count
            if len(audio_segment) == 0:
                if self.is_loaded_playing() and self.loop != 0:
                    self.loop -= 1
                    self.current_frame = self.initial_frame
                else:
                    raise sd.CallbackStop

            out_data[:] = audio_segment.ljust(len(out_data), b'\0')

    def seek(self, value = 0, delta = False):
        # We don't want to do that while stopping
        if not (self.is_loaded_playing() or self.is_loaded_paused()):
            return
        with self.music_lock:
            self.current_frame = max(0, int(delta) * self.current_frame + int(value * self.audio_segment.frame_rate))

    def stop(self, fade_out = 0, wait = False):
        if self.is_loaded_playing():
            ms = int(self.sound_position * 1000)
            ms_fo = max(1, int(fade_out * 1000))

            with self.music_lock:
                self.current_audio_segment = self.current_audio_segment[:ms + ms_fo].fade_out(ms_fo)
                self.stop_playing()
            if wait:
                self.wait_end()
        else:
            self.stop_playing()
            self.stopped()

    def set_gain(self, db_gain):
        if not self.is_not_stopped():
            return

        new_audio_segment = self.current_audio_segment + db_gain

        with self.music_lock:
            self.current_audio_segment = new_audio_segment

    def set_volume(self, value, delta = False):
        [db_gain, self.volume] = gain(value + int(delta) * self.volume, self.volume)

        self.set_gain(db_gain)

    def wait_end(self):
        self.wait_event.clear()
        self.wait_event.wait()

# Add some more functions to AudioSegments
def get_sample_slice_data(self, start_sample=0, end_sample=float('inf')):
    max_val = int(self.frame_count())

    start_i = max(start_sample, 0) * self.frame_width
    end_i =   min(end_sample, max_val) * self.frame_width

    return self._data[start_i:end_i]

pydub.AudioSegment.get_sample_slice_data = get_sample_slice_data