-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.py
390 lines (314 loc) · 14.8 KB
/
controller.py
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import numpy as np
from typing import List, Optional
import sounddevice as sd
from effects import EffectChain
from scipy import signal
from scipy.io import wavfile
class PolymerController:
def __init__(self, bpm: int = 128, sample_rate: int = 44100):
self.bpm = bpm
self.sample_rate = sample_rate
self._update_beat_length()
self.tracks = []
self.track_effects = [] # List of effect chains for each track
self.track_volumes = [] # List of volume levels for each track
self.master_volume = 1.0 # Master volume control
def _update_beat_length(self):
"""Update beat length based on current BPM"""
self.beat_length = 60 / self.bpm
def set_bpm(self, bpm: int):
"""Change the BPM and update all existing tracks
Args:
bpm: New beats per minute value
"""
if bpm <= 0:
raise ValueError("BPM must be positive")
# Calculate time stretch factor
stretch_factor = self.bpm / bpm
# Update BPM and beat length
self.bpm = bpm
self._update_beat_length()
# Time stretch all existing tracks
for i, track in enumerate(self.tracks):
# Calculate new length
new_length = int(len(track) * stretch_factor)
# Resample the track
self.tracks[i] = np.interp(
np.linspace(0, len(track), new_length),
np.arange(len(track)),
track
)
def create_kick(self, pattern: List[int]) -> np.ndarray:
"""Create a kick drum pattern"""
duration = 0.1 # Duration of each kick in seconds
t = np.linspace(0, duration, int(self.sample_rate * duration))
# Create a simple kick drum sound using sine wave with exponential decay
frequency = 150
decay = np.exp(-10 * t)
kick = np.sin(2 * np.pi * frequency * t) * decay
# Create full pattern
pattern_length = len(pattern)
full_pattern = np.zeros(int(self.sample_rate * self.beat_length * pattern_length))
for i, hit in enumerate(pattern):
if hit:
start = int(i * self.sample_rate * self.beat_length)
end = start + len(kick)
full_pattern[start:end] += kick
return full_pattern
def create_hihat(self, pattern: List[int]) -> np.ndarray:
"""Create a hi-hat pattern"""
duration = 0.05 # Duration of each hi-hat in seconds
t = np.linspace(0, duration, int(self.sample_rate * duration))
# Create a noise-based hi-hat sound
noise = np.random.normal(0, 1, len(t))
decay = np.exp(-30 * t)
hihat = noise * decay
# Create full pattern
pattern_length = len(pattern)
full_pattern = np.zeros(int(self.sample_rate * self.beat_length * pattern_length))
for i, hit in enumerate(pattern):
if hit:
start = int(i * self.sample_rate * self.beat_length)
end = start + len(hihat)
full_pattern[start:end] += hihat
return full_pattern
def create_bassline(self, notes: List[float], pattern: List[int]) -> np.ndarray:
"""Create a bassline with given notes and pattern"""
duration = self.beat_length # Duration of each note
pattern_length = len(pattern)
full_pattern = np.zeros(int(self.sample_rate * self.beat_length * pattern_length))
for i, (note, hit) in enumerate(zip(notes, pattern)):
if hit:
t = np.linspace(0, duration, int(self.sample_rate * duration))
frequency = note
decay = np.exp(-5 * t)
wave = np.sin(2 * np.pi * frequency * t) * decay
start = int(i * self.sample_rate * self.beat_length)
end = start + len(wave)
full_pattern[start:end] += wave
return full_pattern
def create_synth(self, notes: List[float], pattern: List[int],
waveform: str = 'sine', attack: float = 0.01,
decay: float = 0.1, sustain: float = 0.7,
release: float = 0.2) -> np.ndarray:
"""Create a synth pattern with ADSR envelope
Args:
notes: List of frequencies in Hz
pattern: List of 1s and 0s indicating when notes should play
waveform: Type of waveform ('sine', 'square', 'sawtooth', 'triangle', 'quad_saw')
attack: Attack time in seconds
decay: Decay time in seconds
sustain: Sustain level (0-1)
release: Release time in seconds
"""
duration = self.beat_length
pattern_length = len(pattern)
full_pattern = np.zeros(int(self.sample_rate * self.beat_length * pattern_length))
for i, (note, hit) in enumerate(zip(notes, pattern)):
if hit:
# Generate time array for this note
t = np.linspace(0, duration, int(self.sample_rate * duration))
# Generate the basic waveform
if waveform == 'sine':
wave = np.sin(2 * np.pi * note * t)
elif waveform == 'square':
wave = np.sign(np.sin(2 * np.pi * note * t))
elif waveform == 'sawtooth':
wave = 2 * (note * t % 1) - 1
elif waveform == 'triangle':
wave = 2 * np.abs(2 * (note * t % 1) - 1) - 1
elif waveform == 'quad_saw':
# Create 4 detuned sawtooth waves
detune_factors = [0.98, 1.0, 1.02, 1.04] # Slight detuning
wave = np.zeros_like(t)
for factor in detune_factors:
detuned_freq = note * factor
wave += 2 * (detuned_freq * t % 1) - 1
wave = wave / len(detune_factors) # Normalize
else:
wave = np.sin(2 * np.pi * note * t) # Default to sine
# Create ADSR envelope
attack_samples = int(attack * self.sample_rate)
decay_samples = int(decay * self.sample_rate)
release_samples = int(release * self.sample_rate)
envelope = np.ones(len(t))
# Attack phase
envelope[:attack_samples] = np.linspace(0, 1, attack_samples)
# Decay phase
envelope[attack_samples:attack_samples + decay_samples] = \
np.linspace(1, sustain, decay_samples)
# Sustain phase is already set to sustain level
# Release phase
envelope[-release_samples:] = \
np.linspace(sustain, 0, release_samples)
# Apply envelope to waveform
wave = wave * envelope
# Add to pattern
start = int(i * self.sample_rate * self.beat_length)
end = start + len(wave)
full_pattern[start:end] += wave
return full_pattern
def create_snare(self, pattern: List[int]) -> np.ndarray:
"""Create a snare drum pattern"""
duration = 0.1
t = np.linspace(0, duration, int(self.sample_rate * duration))
# Mix noise and sine waves for snare sound
noise = np.random.normal(0, 1, len(t))
decay = np.exp(-20 * t)
# Add two sine waves for body
sine1 = np.sin(2 * np.pi * 200 * t)
sine2 = np.sin(2 * np.pi * 180 * t)
snare = (noise + 0.5 * sine1 + 0.5 * sine2) * decay
# Create full pattern
pattern_length = len(pattern)
full_pattern = np.zeros(int(self.sample_rate * self.beat_length * pattern_length))
for i, hit in enumerate(pattern):
if hit:
start = int(i * self.sample_rate * self.beat_length)
end = start + len(snare)
full_pattern[start:end] += snare
return full_pattern
def create_clap(self, pattern: List[int]) -> np.ndarray:
"""Create a clap sound pattern"""
duration = 0.1
t = np.linspace(0, duration, int(self.sample_rate * duration))
# Create multiple short noise bursts
noise = np.random.normal(0, 1, len(t))
# Create multiple decay envelopes slightly offset
decay1 = np.exp(-30 * t)
decay2 = np.roll(decay1, int(0.01 * self.sample_rate))
decay3 = np.roll(decay1, int(0.02 * self.sample_rate))
decay = decay1 + decay2 + decay3
# Apply bandpass filter to noise
clap = noise * decay
nyquist = self.sample_rate / 2
b, a = signal.butter(2, [1000/nyquist, 4000/nyquist], btype='band')
clap = signal.filtfilt(b, a, clap)
# Create full pattern
pattern_length = len(pattern)
full_pattern = np.zeros(int(self.sample_rate * self.beat_length * pattern_length))
for i, hit in enumerate(pattern):
if hit:
start = int(i * self.sample_rate * self.beat_length)
end = start + len(clap)
full_pattern[start:end] += clap
return full_pattern
def create_shaker(self, pattern: List[int]) -> np.ndarray:
"""Create a shaker pattern
Args:
pattern: List of 1s and 0s indicating when shaker should play
Returns:
np.ndarray: The generated shaker pattern
"""
duration = 0.08 # Duration of each shaker sound in seconds
t = np.linspace(0, duration, int(self.sample_rate * duration))
# Create noise-based shaker sound
noise = np.random.normal(0, 1, len(t))
# Quick attack, quick decay envelope
envelope = np.exp(-40 * t) # Faster decay than hi-hat
# Apply bandpass filter to create characteristic shaker sound
nyquist = self.sample_rate / 2
b, a = signal.butter(2, [3000/nyquist, 7000/nyquist], btype='band')
shaker = signal.filtfilt(b, a, noise * envelope)
# Create full pattern
pattern_length = len(pattern)
full_pattern = np.zeros(int(self.sample_rate * self.beat_length * pattern_length))
for i, hit in enumerate(pattern):
if hit:
start = int(i * self.sample_rate * self.beat_length)
end = start + len(shaker)
full_pattern[start:end] += shaker
return full_pattern
def add_track(self, track: np.ndarray, effects: Optional[EffectChain] = None, volume: float = 1.0):
"""Add a track to the composition with optional effects and volume
Args:
track: Audio track data
effects: Optional effect chain to apply to the track
volume: Volume level for the track (0.0 to 1.0)
"""
self.tracks.append(track)
self.track_effects.append(effects if effects else EffectChain())
self.track_volumes.append(max(0.0, min(1.0, volume))) # Clamp volume between 0 and 1
def set_track_volume(self, track_index: int, volume: float):
"""Set the volume for a specific track
Args:
track_index: Index of the track to adjust
volume: New volume level (0.0 to 1.0)
"""
if 0 <= track_index < len(self.tracks):
self.track_volumes[track_index] = max(0.0, min(1.0, volume))
def set_master_volume(self, volume: float):
"""Set the master volume level
Args:
volume: New master volume level (0.0 to 1.0)
"""
self.master_volume = max(0.0, min(1.0, volume))
def mix(self) -> np.ndarray:
"""Mix all tracks together with their effects and volume levels"""
if not self.tracks:
return np.array([])
max_length = max(len(track) for track in self.tracks)
mixed = np.zeros(max_length)
for track, effects, volume in zip(self.tracks, self.track_effects, self.track_volumes):
# Process track through its effect chain
processed = effects.process(track, self.sample_rate)
# Apply track volume
processed = processed * volume
mixed[:len(processed)] += processed
# Apply master volume
mixed = mixed * self.master_volume
# Normalize if the signal exceeds [-1, 1]
max_amplitude = np.max(np.abs(mixed))
if max_amplitude > 1.0:
mixed = mixed / max_amplitude
return mixed
def play(self):
"""Play the mixed composition"""
mixed = self.mix()
sd.play(mixed, self.sample_rate)
sd.wait()
def loop(self):
"""Loop the composition continuously without gaps"""
mixed = self.mix() # Mix once outside the loop
# Keep track of current position in the audio
position = 0
def callback(outdata, frames, time, status):
nonlocal position
if status:
print(status)
# Calculate how many samples we need
remaining = len(mixed) - position
if remaining >= frames:
# We have enough samples remaining
outdata[:] = mixed[position:position + frames].reshape(-1, 1)
position += frames
else:
# We need to wrap around to the beginning
# First, fill with remaining samples
outdata[:remaining] = mixed[position:].reshape(-1, 1)
# Then fill the rest from the beginning
outdata[remaining:] = mixed[:frames-remaining].reshape(-1, 1)
position = frames - remaining
# Reset position if we've reached the end
if position >= len(mixed):
position = 0
# Create continuous stream
stream = sd.OutputStream(
samplerate=self.sample_rate,
channels=2,
callback=callback,
finished_callback=None
)
with stream:
stream.start()
while True:
sd.sleep(100)
def export(self, filename: str):
"""Export the mixed composition to a WAV file
Args:
filename: Path to save the WAV file
"""
mixed = self.mix()
# Ensure the audio is in the correct range (-1 to 1) and convert to 32-bit float
mixed = np.clip(mixed, -1, 1).astype(np.float32)
wavfile.write(filename, self.sample_rate, mixed)