forked from lordmauve/pyfxr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyfxr.py
595 lines (474 loc) · 16.1 KB
/
pyfxr.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
import re
import math
import random
from functools import lru_cache
from typing import Tuple, Union, Optional, Dict
from enum import Enum
import _pyfxr
from _pyfxr import SoundBuffer, Wavetable, sfx, CachedSound, chord
__all__ = (
'SAMPLE_RATE',
'SoundBuffer',
'Wavetable',
'SFX',
'pickup',
'laser',
'explosion',
'powerup',
'hurt',
'jump',
'select',
'tone',
'pluck',
'note_to_hertz',
'chord',
'simple_chord',
)
#: The sample rate for all sounds generated by pyfxr
SAMPLE_RATE: int = 44100
NOTE_PATTERN = re.compile(r'^([A-G])([b#]?)([0-8])$')
A4 = 440.0
NOTE_VALUE = dict(C=-9, D=-7, E=-5, F=-4, G=-2, A=0, B=2)
TWELFTH_ROOT = math.pow(2, (1 / 12))
@lru_cache()
def note_to_hertz(note: str) -> float:
"""Get a frequency for a given note.
Here we use an even temper - all semitones in the octave are equally
spaced twelfth powers of 2.
"""
note, accidental, octave = validate_note(note)
value = note_value(note, accidental, octave)
return A4 * math.pow(TWELFTH_ROOT, value)
# Regex to match chords
CHORD_PATTERN = re.compile(r'^([A-G])([b#]?)(M?7?|[m-]7?|(?:dim|o)|\+)$')
# The chords in integer notation
CHORDS = {
# Major
'': (0, 4, 7),
'M': (0, 4, 7),
# Minor
'm': (0, 3, 7),
'-': (0, 3, 7),
# Dominant 7th
'7': (0, 4, 7, 10),
# Major 7th
'M7': (0, 4, 7, 11),
# Minor 7th
'm7': (0, 3, 7, 10),
'-7': (0, 3, 7, 10),
# Diminished 7th
'dim': (0, 3, 6, 9),
'o': (0, 3, 6, 9),
# Augmented 7th
'+': (0, 4, 8),
}
def simple_chord(
name: str,
attack: float = 0.1,
decay: float = 0.1,
sustain: float = 0.75,
release: float = 0.25,
wavetable: Wavetable = Wavetable.sine(),
stagger: float = 0.0,
) -> SoundBuffer:
"""Construct a chord using a chord name like
* `C` - major chord in C
* `Bbm` or `Bb-` - minor chord in B-flat
* `D7` - dominant 7th
etc.
Other parameters are as for :func:`tone` and `:func:`chord`.
"""
mo = CHORD_PATTERN.match(name)
if not mo:
raise ValueError(
f"{name} is not a valid chord."
'The key is A-F, either normal, flat (b) or sharp (#) '
'and then a chord type like minor (m), dominant 7th (7), '
'diminished 7th (dim), or nothing for a major chord.'
)
key, accidental, type = mo.groups()
value = note_value(key, accidental, 3)
tones = CHORDS[type]
pitches = [A4 * math.pow(TWELFTH_ROOT, value + i) for i in tones]
sounds = [
_pyfxr.tone(
wavetable,
pitch,
attack * 44100,
decay * 44100,
sustain * 44100,
release * 44100,
)
for pitch in pitches
]
random.shuffle(sounds)
return chord(sounds, stagger=stagger)
def note_value(note: str, accidental: str, octave: int) -> int:
"""Given a note name, an accidental and an octave, return a note number.
Each number corresponds to a specific note and can be converted to a pitch.
"""
value = NOTE_VALUE[note]
if accidental:
value += 1 if accidental == '#' else -1
return (4 - octave) * -12 + value
def validate_note(note: str) -> Tuple[str, str, int]:
match = re.match(NOTE_PATTERN, note)
if match is None:
raise ValueError(
'%s is not a valid note. '
'notes are A-F, are either normal, flat (b) or sharp (#) '
'and of octave 0-8' % note
)
note, accidental, octave = match.group(1, 2, 3)
return note, accidental, int(octave)
def pluck(
duration: float,
pitch: Union[float, str],
release: float = 0.1
) -> SoundBuffer:
"""Generate a pluck sound, like a harp or guitar."""
# This is a wrapper to handle converting a note string to a pitch
if isinstance(pitch, str):
pitch = note_to_hertz(pitch)
return _pyfxr.pluck(duration, pitch, release)
pluck.__doc__ = _pyfxr.pluck.__doc__
def tone(
pitch: Union[float, str] = 440.0, # Hz, default = A
attack: float = 0.1,
decay: float = 0.1,
sustain: float = 0.75,
release: float = 0.25,
wavetable: Wavetable = Wavetable.sine(),
) -> SoundBuffer:
"""Generate a tone using a wavetable.
The tone will be modulated by an ADSR envelope
(attack-decay-sustain-release) which gives the tone a more natural feel,
and avoids clicks when played. The total length of the tone is the sum of
these durations.
:param wavetable: The wavetable to use (default is a sine wave).
:param pitch: The pitch of the tone to generate, either float Hz or a note
name/number like ``Bb4`` for B-flat in the 4th octave.
:param attack: Attack time in seconds
:param decay: Decay time in seconds
:param sustain: Sustain time in seconds
:param release: Release time in seconds
"""
# This is a wrapper to handle converting a note string to a pitch
if isinstance(pitch, str):
pitch = note_to_hertz(pitch)
return _pyfxr.tone(
wavetable,
pitch,
attack * 44100,
decay * 44100,
sustain * 44100,
release * 44100,
)
class FloatParam:
"""A parameter for a sound effect."""
name: str
default: float
#: If True, then accept negative numbers for the parameter
bipolar: bool
def __init__(
self,
default: float = 0.0,
*,
bipolar: bool = False
):
self.default = default
self.bipolar = bipolar
self.name = None
def __set_name__(self, cls: type, name: str):
self.name = name
def __get__(self, inst: 'SFX', cls: type) -> float:
return inst._params.get(self.name, self.default)
def __set__(self, inst: 'SFX', value: float):
value = float(value)
if value < 0.0 and not self.bipolar:
raise ValueError(
f"Negative values are not value for {self.name}"
)
inst._params[self.name] = value
inst._clear()
def __delete__(self, inst: 'SFX'):
inst._params.pop(self.name, None)
inst._clear()
class WaveType(Enum):
"""The wave types available for the SFX builder.
Pure tones with tone() use arbitrary wavetables rather than this
enumeration.
"""
#: A square-wave waveform
SQUARE = 0
#: A saw-wave waveform
SAW = 1
#: A sine wave
SINE = 2
#: Random noise
NOISE = 3
class SFX(CachedSound):
"""Build a sound effect using a set of parameters.
The list of parameters is long and the sensible ranges for the parameters
aren't that clear. This class acts as a validator and builder for the
parameters, making it simpler to experiment with sound effects.
You can also serialise this class in several ways:
* The ``repr()`` is suitable for pasting into code.
* You can serialise it as JSON using ``.as_dict()``.
* You can pickle the class.
In any of these case the size is much smaller than the generated
SoundBuffer.
SFX supports the buffer protocol much like :class:`SoundBuffer`; accessing
the object as a buffer generates and caches a sound.
"""
#: The initial frequency of the sound
base_freq: float = FloatParam(0.3)
#: The minimum frequency of the sound
freq_limit: float = FloatParam(0.0)
#: The rate of change of the frequency of the sound
freq_ramp: float = FloatParam(0.0, bipolar=True)
#: The acceleration of the change in frequency of the sound
freq_dramp: float = FloatParam(0.0, bipolar=True)
#: If using square wave, the duty cycle of the waveform
duty: float = FloatParam(0.0)
#: The rate of change of the square wave duty cycle
duty_ramp: float = FloatParam(0.0, bipolar=True)
#: Vibrato strength
vib_strength: float = FloatParam(0.0)
#: Vibrato speed
vib_speed: float = FloatParam(0.0)
#: Vibrato delay
vib_delay: float = FloatParam(0.0)
#: The duration of the attack phase of the ADSR envelope
env_attack: float = FloatParam(0.0)
#: The duration of the sustain phase of the ADSR envelope
env_sustain: float = FloatParam(0.3)
#: The duration of the decay phase of the ADSR envelope
env_decay: float = FloatParam(0.4)
#: Causes the volume to decrease during the sustain phase of the envelope
env_punch: float = FloatParam(0.0)
#: Low-pass filter resonance
lpf_resonance: float = FloatParam(0.0)
#: Low-pass filter cutoff frequency
lpf_freq: float = FloatParam(1.0)
#: Low-pass filter cutoff ramp
lpf_ramp: float = FloatParam(0.0, bipolar=True)
#: High-pass filter frequency
hpf_freq: float = FloatParam(0.0)
#: High-pass filter ramp
hpf_ramp: float = FloatParam(0.0, bipolar=True)
#: Phaser offset
pha_offset: float = FloatParam(0.0, bipolar=True)
#: Phaser ramp
pha_ramp: float = FloatParam(0.0, bipolar=True)
#: Repeat speed
repeat_speed: float = FloatParam(0.0)
#: Arpeggio speed
arp_speed: float = FloatParam(0.0)
#: Arpeggio mod
arp_mod: float = FloatParam(0.0, bipolar=True)
__slots__ = '_params'
def __init__(self, **kwargs):
self._params = {}
for k, v in kwargs.items():
setattr(self, k, v)
@property
def wave_type(self) -> WaveType:
"""Get the wave type."""
return WaveType(self._params.get('wave_type', 0))
@wave_type.setter
def wave_type(self, v: Union[str, int, WaveType]):
"""Set the wave type."""
if isinstance(v, str):
v = WaveType[v.upper()]
self._params['wave_type'] = WaveType(v).value
self._clear()
def as_dict(self) -> dict:
"""Get the parameters as a dict.
The dict is suitable for serialising as JSON; to reconstruct the
object, pass the parameters as kwargs to the constructor, eg.
>>> s = SFX(...)
>>> params = s.as_dict()
>>> s2 = SFX(**params)
"""
return self._params.copy()
def __repr__(self):
"""Generate a repr for this sound effect.
The repr is guaranteed to be executable code to reconstruct the SFX
instance.
"""
params = [f'{type(self).__module__}.{type(self).__qualname__}(']
for k, desc in vars(type(self)).items():
if k != 'wave_type' and not isinstance(desc, FloatParam):
continue
try:
value = self._params[k]
except KeyError:
continue
r = repr(value)
if k == 'wave_type':
value = WaveType(value)
r = f'{value.__module__}.{value}'
params.append(f' {k}={r},')
if len(params) == 1:
return params[0] + ')'
params.append(')')
return '\n'.join(params)
def get_queue_source(self):
# Duck type as a pyglet.media.Source.
# Don't put a docstring here as it causes the method to appear in
# the docs.
return self._get().get_queue_source()
def _build(self) -> SoundBuffer:
"""Actually generate the sound using the current parameters."""
return sfx(**{
f'p_{k}' if k != 'wave_type' else k: v
for k, v in self._params.items()
})
def build(self) -> SoundBuffer:
"""Get the generated sound (memoised)."""
return self._get()
def envelope(
self,
attack: float = 0.0,
sustain: float = 0.3,
decay: float = 0.4,
punch: float = 0.0
):
"""Set the ADSR envelope for this sound effect."""
self.env_attack = attack
self.env_sustain = sustain
self.env_decay = decay
self.env_punch = punch
return self
def one_in(n: int) -> bool:
"""Return True with odds of 1 in n."""
return not random.randint(0, n)
def _mksfx(params: Dict[str, float]) -> SFX:
"""Round the parameters and construct an SFX.
Rounding is helpful because it makes the repr shorter and more
human-friendly.
"""
return SFX(**{k: round(v, 3) for k, v in params.items()})
def pickup() -> SFX:
"""Generate a random bell sound, like picking up a coin."""
base_freq = random.uniform(0.4, 0.9)
env_attack = 0.0
env_sustain = random.uniform(0.0, 0.1)
env_decay = random.uniform(0.1, 0.5)
env_punch = random.uniform(0.3, 0.6)
if one_in(2):
arp_mod = random.uniform(0.2, 0.6)
return _mksfx(locals())
def laser() -> SFX:
"""Generate a random laser sound."""
wave_type = random.choice((0, 0, 1, 1, 2))
base_freq = random.uniform(0.5, 1.0)
freq_limit = max(0.2, base_freq - random.uniform(0.2, 0.8))
freq_ramp = random.uniform(-0.35, -0.15)
if one_in(3):
base_freq = random.uniform(0.3, 0.9)
freq_limit = random.uniform(0.0, 0.1)
freq_ramp = random.uniform(-0.65, -0.35)
if one_in(2):
duty = random.uniform(0.0, 0.5)
duty_ramp = random.uniform(0.0, 0.2)
else:
duty = random.uniform(0.4, 0.9)
duty_ramp = random.uniform(-0.7, 0.0)
env_attack = 0.0
env_sustain = random.uniform(0.1, 0.3)
env_decay = random.uniform(0.0, 0.4)
if one_in(2):
env_punch = random.uniform(0.0, 0.3)
if one_in(3):
pha_offset = random.uniform(0.0, 0.2)
pha_ramp = random.uniform(-0.2, 0.0)
if one_in(2):
hpf_freq = random.uniform(0.0, 0.3)
return _mksfx(locals())
def explosion() -> SFX:
"""Generate a random explosion sound."""
wave_type = 3
if one_in(2):
base_freq = random.uniform(0.1, 0.5) ** 2
freq_ramp = random.uniform(-0.1, 0.3)
else:
base_freq = random.uniform(0.2, 0.7) ** 2
freq_ramp = random.uniform(-0.4, -0.2)
if one_in(5):
freq_ramp = 0
if one_in(3):
repeat_speed = random.uniform(0.3, 0.8)
env_attack = 0.0
env_sustain = random.uniform(0.1, 0.4)
env_decay = random.uniform(0.0, 0.5)
if one_in(2):
pha_offset = random.uniform(-0.3, 0.6)
pha_ramp = random.uniform(-0.3, 0)
env_punch = random.uniform(0.2, 0.6)
if one_in(2):
vib_strength = random.uniform(0.0, 0.7)
vib_speed = random.uniform(0.0, 0.6)
if one_in(3):
arp_speed = random.uniform(0.6, 0.9)
arp_mod = random.uniform(-0.8, 0.8)
return _mksfx(locals())
def powerup() -> SFX:
"""Generate a random chime, like receiving a power-up."""
if one_in(2):
wave_type = 1
else:
duty = random.uniform(0.0, 0.6)
if one_in(2):
base_freq = random.uniform(0.2, 0.5)
freq_ramp = random.uniform(0.1, 0.5)
repeat_speed = random.uniform(0.4, 0.8)
else:
base_freq = random.uniform(0.2, 0.5)
freq_ramp = random.uniform(0.05, 0.25)
if one_in(2):
vib_strength = random.uniform(0.0, 0.7)
vib_speed = random.uniform(0.0, 0.6)
env_attack = 0.0
env_sustain = random.uniform(0.0, 0.4)
env_decay = random.uniform(0.1, 0.5)
return _mksfx(locals())
def hurt() -> SFX:
"""Generate a random impact sound, like a character being hurt."""
wave_type = random.choice([0, 1, 3])
if wave_type == 0:
duty = random.uniform(0, 0.6)
base_freq = random.uniform(0.2, 0.8)
freq_ramp = random.uniform(-0.7, -0.3)
env_attack = 0.0
env_sustain = random.uniform(0.0, 0.1)
env_decay = random.uniform(0.1, 0.3)
if one_in(2):
hpf_freq = random.uniform(0.0, 0.3)
return _mksfx(locals())
def jump() -> SFX:
"""Generate a random jump sound."""
wave_type = 0
duty = random.uniform(0.0, 0.6)
base_freq = random.uniform(0.3, 0.6)
freq_ramp = random.uniform(0.1, 0.3)
env_attack = 0.0
env_sustain = random.uniform(0.1, 0.4)
env_decay = random.uniform(0.1, 0.3)
if one_in(2):
hpf_freq = random.uniform(0.0, 0.3)
if one_in(2):
lpf_freq = random.uniform(0.4, 1.0)
return _mksfx(locals())
def select() -> SFX:
"""Generate a random 'blip' noise, like selecting an option in a menu."""
wave_type = random.choice([0, 1])
if wave_type == 0:
duty = random.uniform(0.0, 0.6)
base_freq = random.uniform(0.2, 0.6)
env_attack = 0.0
env_sustain = random.uniform(0.1, 0.2)
env_decay = random.uniform(0.0, 0.2)
hpf_freq = 0.1
return _mksfx(locals())