-
Notifications
You must be signed in to change notification settings - Fork 79
/
transform.py
2401 lines (1926 loc) · 85.6 KB
/
transform.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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Python wrapper around the SoX library.
This module requires that SoX is installed.
'''
from __future__ import print_function
import logging
import random
from .core import ENCODING_VALS
from .core import is_number
from .core import play
from .core import sox
from .core import SoxError
from .core import VALID_FORMATS
from . import file_info
logging.basicConfig(level=logging.DEBUG)
VERBOSITY_VALS = [0, 1, 2, 3, 4]
class Transformer(object):
'''Audio file transformer.
Class which allows multiple effects to be chained to create an output
file, saved to output_filepath.
Methods
-------
set_globals
Overwrite the default global arguments.
build
Execute the current chain of commands and write output file.
'''
def __init__(self):
'''
Attributes
----------
input_format : list of str
Input file format arguments that will be passed to SoX.
output_format : list of str
Output file format arguments that will be bassed to SoX.
effects : list of str
Effects arguments that will be passed to SoX.
effects_log : list of str
Ordered sequence of effects applied.
globals : list of str
Global arguments that will be passed to SoX.
'''
self.input_format = []
self.output_format = []
self.effects = []
self.effects_log = []
self.globals = []
self.set_globals()
def set_globals(self, dither=False, guard=False, multithread=False,
replay_gain=False, verbosity=2):
'''Sets SoX's global arguments.
Overwrites any previously set global arguments.
If this function is not explicity called, globals are set to this
function's defaults.
Parameters
----------
dither : bool, default=False
If True, dithering is applied for low files with low bit rates.
guard : bool, default=False
If True, invokes the gain effect to guard against clipping.
multithread : bool, default=False
If True, each channel is processed in parallel.
replay_gain : bool, default=False
If True, applies replay-gain adjustment to input-files.
verbosity : int, default=2
SoX's verbosity level. One of:
* 0 : No messages are shown at all
* 1 : Only error messages are shown. These are generated if SoX
cannot complete the requested commands.
* 2 : Warning messages are also shown. These are generated if
SoX can complete the requested commands, but not exactly
according to the requested command parameters, or if
clipping occurs.
* 3 : Descriptions of SoX’s processing phases are also shown.
Useful for seeing exactly how SoX is processing your audio.
* 4, >4 : Messages to help with debugging SoX are also shown.
'''
if not isinstance(dither, bool):
raise ValueError('dither must be a boolean.')
if not isinstance(guard, bool):
raise ValueError('guard must be a boolean.')
if not isinstance(multithread, bool):
raise ValueError('multithread must be a boolean.')
if not isinstance(replay_gain, bool):
raise ValueError('replay_gain must be a boolean.')
if verbosity not in VERBOSITY_VALS:
raise ValueError(
'Invalid value for VERBOSITY. Must be one {}'.format(
VERBOSITY_VALS)
)
global_args = []
if not dither:
global_args.append('-D')
if guard:
global_args.append('-G')
if multithread:
global_args.append('--multi-threaded')
if replay_gain:
global_args.append('--replay-gain')
global_args.append('track')
global_args.append('-V{}'.format(verbosity))
self.globals = global_args
return self
def set_input_format(self, file_type=None, rate=None, bits=None,
channels=None, encoding=None, ignore_length=False):
'''Sets input file format arguments. This is primarily useful when
dealing with audio files without a file extension. Overwrites any
previously set input file arguments.
If this function is not explicity called the input format is inferred
from the file extension or the file's header.
Parameters
----------
file_type : str or None, default=None
The file type of the input audio file. Should be the same as what
the file extension would be, for ex. 'mp3' or 'wav'.
rate : float or None, default=None
The sample rate of the input audio file. If None the sample rate
is inferred.
bits : int or None, default=None
The number of bits per sample. If None, the number of bits per
sample is inferred.
channels : int or None, default=None
The number of channels in the audio file. If None the number of
channels is inferred.
encoding : str or None, default=None
The audio encoding type. Sometimes needed with file-types that
support more than one encoding type. One of:
* signed-integer : PCM data stored as signed (‘two’s
complement’) integers. Commonly used with a 16 or 24−bit
encoding size. A value of 0 represents minimum signal
power.
* unsigned-integer : PCM data stored as unsigned integers.
Commonly used with an 8-bit encoding size. A value of 0
represents maximum signal power.
* floating-point : PCM data stored as IEEE 753 single precision
(32-bit) or double precision (64-bit) floating-point
(‘real’) numbers. A value of 0 represents minimum signal
power.
* a-law : International telephony standard for logarithmic
encoding to 8 bits per sample. It has a precision
equivalent to roughly 13-bit PCM and is sometimes encoded
with reversed bit-ordering.
* u-law : North American telephony standard for logarithmic
encoding to 8 bits per sample. A.k.a. μ-law. It has a
precision equivalent to roughly 14-bit PCM and is sometimes
encoded with reversed bit-ordering.
* oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM;
it has a precision equivalent to roughly 12-bit PCM. ADPCM
is a form of audio compression that has a good compromise
between audio quality and encoding/decoding speed.
* ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision
equivalent to roughly 13-bit PCM.
* ms-adpcm : Microsoft 4-bit ADPCM; it has a precision
equivalent to roughly 14-bit PCM.
* gsm-full-rate : GSM is currently used for the vast majority
of the world’s digital wireless telephone calls. It
utilises several audio formats with different bit-rates and
associated speech quality. SoX has support for GSM’s
original 13kbps ‘Full Rate’ audio format. It is usually
CPU-intensive to work with GSM audio.
ignore_length : bool, default=False
If True, overrides an (incorrect) audio length given in an audio
file’s header. If this option is given then SoX will keep reading
audio until it reaches the end of the input file.
'''
if file_type not in VALID_FORMATS + [None]:
raise ValueError(
'Invalid file_type. Must be one of {}'.format(VALID_FORMATS)
)
if not is_number(rate) and rate is not None:
raise ValueError('rate must be a float or None')
if rate is not None and rate <= 0:
raise ValueError('rate must be a positive number')
if not isinstance(bits, int) and bits is not None:
raise ValueError('bits must be an int or None')
if bits is not None and bits <= 0:
raise ValueError('bits must be a positive number')
if not isinstance(channels, int) and channels is not None:
raise ValueError('channels must be an int or None')
if channels is not None and channels <= 0:
raise ValueError('channels must be a positive number')
if encoding not in ENCODING_VALS + [None]:
raise ValueError(
'Invalid encoding. Must be one of {}'.format(ENCODING_VALS)
)
if not isinstance(ignore_length, bool):
raise ValueError('ignore_length must be a boolean')
input_format = []
if file_type is not None:
input_format.extend(['-t', '{}'.format(file_type)])
if rate is not None:
input_format.extend(['-r', '{}'.format(rate)])
if bits is not None:
input_format.extend(['-b', '{}'.format(bits)])
if channels is not None:
input_format.extend(['-c', '{}'.format(channels)])
if encoding is not None:
input_format.extend(['-e', '{}'.format(encoding)])
if ignore_length:
input_format.append('--ignore-length')
self.input_format = input_format
return self
def set_output_format(self, file_type=None, rate=None, bits=None,
channels=None, encoding=None, comments=None,
append_comments=True):
'''Sets output file format arguments. These arguments will overwrite
any format related arguments supplied by other effects (e.g. rate).
If this function is not explicity called the output format is inferred
from the file extension or the file's header.
Parameters
----------
file_type : str or None, default=None
The file type of the output audio file. Should be the same as what
the file extension would be, for ex. 'mp3' or 'wav'.
rate : float or None, default=None
The sample rate of the output audio file. If None the sample rate
is inferred.
bits : int or None, default=None
The number of bits per sample. If None, the number of bits per
sample is inferred.
channels : int or None, default=None
The number of channels in the audio file. If None the number of
channels is inferred.
encoding : str or None, default=None
The audio encoding type. Sometimes needed with file-types that
support more than one encoding type. One of:
* signed-integer : PCM data stored as signed (‘two’s
complement’) integers. Commonly used with a 16 or 24−bit
encoding size. A value of 0 represents minimum signal
power.
* unsigned-integer : PCM data stored as unsigned integers.
Commonly used with an 8-bit encoding size. A value of 0
represents maximum signal power.
* floating-point : PCM data stored as IEEE 753 single precision
(32-bit) or double precision (64-bit) floating-point
(‘real’) numbers. A value of 0 represents minimum signal
power.
* a-law : International telephony standard for logarithmic
encoding to 8 bits per sample. It has a precision
equivalent to roughly 13-bit PCM and is sometimes encoded
with reversed bit-ordering.
* u-law : North American telephony standard for logarithmic
encoding to 8 bits per sample. A.k.a. μ-law. It has a
precision equivalent to roughly 14-bit PCM and is sometimes
encoded with reversed bit-ordering.
* oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM;
it has a precision equivalent to roughly 12-bit PCM. ADPCM
is a form of audio compression that has a good compromise
between audio quality and encoding/decoding speed.
* ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision
equivalent to roughly 13-bit PCM.
* ms-adpcm : Microsoft 4-bit ADPCM; it has a precision
equivalent to roughly 14-bit PCM.
* gsm-full-rate : GSM is currently used for the vast majority
of the world’s digital wireless telephone calls. It
utilises several audio formats with different bit-rates and
associated speech quality. SoX has support for GSM’s
original 13kbps ‘Full Rate’ audio format. It is usually
CPU-intensive to work with GSM audio.
comments : str or None, default=None
If not None, the string is added as a comment in the header of the
output audio file. If None, no comments are added.
append_comments : bool, default=True
If True, comment strings are appended to SoX's default comments. If
False, the supplied comment replaces the existing comment.
'''
if file_type not in VALID_FORMATS + [None]:
raise ValueError(
'Invalid file_type. Must be one of {}'.format(VALID_FORMATS)
)
if not is_number(rate) and rate is not None:
raise ValueError('rate must be a float or None')
if rate is not None and rate <= 0:
raise ValueError('rate must be a positive number')
if not isinstance(bits, int) and bits is not None:
raise ValueError('bits must be an int or None')
if bits is not None and bits <= 0:
raise ValueError('bits must be a positive number')
if not isinstance(channels, int) and channels is not None:
raise ValueError('channels must be an int or None')
if channels is not None and channels <= 0:
raise ValueError('channels must be a positive number')
if encoding not in ENCODING_VALS + [None]:
raise ValueError(
'Invalid encoding. Must be one of {}'.format(ENCODING_VALS)
)
if comments is not None and not isinstance(comments, str):
raise ValueError('comments must be a string or None')
if not isinstance(append_comments, bool):
raise ValueError('append_comments must be a boolean')
output_format = []
if file_type is not None:
output_format.extend(['-t', '{}'.format(file_type)])
if rate is not None:
output_format.extend(['-r', '{}'.format(rate)])
if bits is not None:
output_format.extend(['-b', '{}'.format(bits)])
if channels is not None:
output_format.extend(['-c', '{}'.format(channels)])
if encoding is not None:
output_format.extend(['-e', '{}'.format(encoding)])
if comments is not None:
if append_comments:
output_format.extend(['--add-comment', comments])
else:
output_format.extend(['--comment', comments])
self.output_format = output_format
return self
def build(self, input_filepath, output_filepath):
'''Builds the output_file by executing the current set of commands.
Parameters
----------
input_filepath : str
Path to input audio file.
output_filepath : str
Path to desired output file. If a file already exists at the given
path, the file will be overwritten.
'''
file_info.validate_input_file(input_filepath)
file_info.validate_output_file(output_filepath)
args = []
args.extend(self.globals)
args.extend(self.input_format)
args.append(input_filepath)
args.extend(self.output_format)
args.append(output_filepath)
args.extend(self.effects)
status, out, err = sox(args)
if status != 0:
raise SoxError(
"Stdout: {}\nStderr: {}".format(out, err)
)
else:
logging.info(
"Created %s with effects: %s",
output_filepath,
" ".join(self.effects_log)
)
if out is not None:
logging.info("[SoX] {}".format(out))
return True
def preview(self, input_filepath):
'''Play a preview of the output with the current set of effects
'''
args = ["play", "--no-show-progress"]
args.extend(self.globals)
args.extend(self.input_format)
args.append(input_filepath)
args.extend(self.effects)
play(args)
def allpass(self, frequency, width_q=2.0):
'''Apply a two-pole all-pass filter. An all-pass filter changes the
audio’s frequency to phase relationship without changing its frequency
to amplitude relationship. The filter is described in detail in at
http://musicdsp.org/files/Audio-EQ-Cookbook.txt
Parameters
----------
frequency : float
The filter's center frequency in Hz.
width_q : float, default=2.0
The filter's width as a Q-factor.
See Also
--------
equalizer, highpass, lowpass, sinc
'''
if not is_number(frequency) or frequency <= 0:
raise ValueError("frequency must be a positive number.")
if not is_number(width_q) or width_q <= 0:
raise ValueError("width_q must be a positive number.")
effect_args = [
'allpass', '{}'.format(frequency), '{}q'.format(width_q)
]
self.effects.extend(effect_args)
self.effects_log.append('allpass')
return self
def bandpass(self, frequency, width_q=2.0, constant_skirt=False):
'''Apply a two-pole Butterworth band-pass filter with the given central
frequency, and (3dB-point) band-width. The filter rolls off at 6dB per
octave (20dB per decade) and is described in detail in
http://musicdsp.org/files/Audio-EQ-Cookbook.txt
Parameters
----------
frequency : float
The filter's center frequency in Hz.
width_q : float, default=2.0
The filter's width as a Q-factor.
constant_skirt : bool, default=False
If True, selects constant skirt gain (peak gain = width_q).
If False, selects constant 0dB peak gain.
See Also
--------
bandreject, sinc
'''
if not is_number(frequency) or frequency <= 0:
raise ValueError("frequency must be a positive number.")
if not is_number(width_q) or width_q <= 0:
raise ValueError("width_q must be a positive number.")
if not isinstance(constant_skirt, bool):
raise ValueError("constant_skirt must be a boolean.")
effect_args = ['bandpass']
if constant_skirt:
effect_args.append('-c')
effect_args.extend(['{}'.format(frequency), '{}q'.format(width_q)])
self.effects.extend(effect_args)
self.effects_log.append('bandpass')
return self
def bandreject(self, frequency, width_q=2.0):
'''Apply a two-pole Butterworth band-reject filter with the given
central frequency, and (3dB-point) band-width. The filter rolls off at
6dB per octave (20dB per decade) and is described in detail in
http://musicdsp.org/files/Audio-EQ-Cookbook.txt
Parameters
----------
frequency : float
The filter's center frequency in Hz.
width_q : float, default=2.0
The filter's width as a Q-factor.
constant_skirt : bool, default=False
If True, selects constant skirt gain (peak gain = width_q).
If False, selects constant 0dB peak gain.
See Also
--------
bandreject, sinc
'''
if not is_number(frequency) or frequency <= 0:
raise ValueError("frequency must be a positive number.")
if not is_number(width_q) or width_q <= 0:
raise ValueError("width_q must be a positive number.")
effect_args = [
'bandreject', '{}'.format(frequency), '{}q'.format(width_q)
]
self.effects.extend(effect_args)
self.effects_log.append('bandreject')
return self
def bass(self, gain_db, frequency=100.0, slope=0.5):
'''Boost or cut the bass (lower) frequencies of the audio using a
two-pole shelving filter with a response similar to that of a standard
hi-fi’s tone-controls. This is also known as shelving equalisation.
The filters are described in detail in
http://musicdsp.org/files/Audio-EQ-Cookbook.txt
Parameters
----------
gain_db : float
The gain at 0 Hz.
For a large cut use -20, for a large boost use 20.
frequency : float, default=100.0
The filter's cutoff frequency in Hz.
slope : float, default=0.5
The steepness of the filter's shelf transition.
For a gentle slope use 0.3, and use 1.0 for a steep slope.
See Also
--------
treble, equalizer
'''
if not is_number(gain_db):
raise ValueError("gain_db must be a number")
if not is_number(frequency) or frequency <= 0:
raise ValueError("frequency must be a positive number.")
if not is_number(slope) or slope <= 0 or slope > 1.0:
raise ValueError("width_q must be a positive number.")
effect_args = [
'bass', '{}'.format(gain_db), '{}'.format(frequency),
'{}s'.format(slope)
]
self.effects.extend(effect_args)
self.effects_log.append('bass')
return self
def bend(self):
raise NotImplementedError
def biquad(self, b, a):
'''Apply a biquad IIR filter with the given coefficients.
Parameters
----------
b : list of floats
Numerator coefficients. Must be length 3
a : list of floats
Denominator coefficients. Must be length 3
See Also
--------
fir, treble, bass, equalizer
'''
if not isinstance(b, list):
raise ValueError('b must be a list.')
if not isinstance(a, list):
raise ValueError('a must be a list.')
if len(b) != 3:
raise ValueError('b must be a length 3 list.')
if len(a) != 3:
raise ValueError('a must be a length 3 list.')
if not all([is_number(b_val) for b_val in b]):
raise ValueError('all elements of b must be numbers.')
if not all([is_number(a_val) for a_val in a]):
raise ValueError('all elements of a must be numbers.')
effect_args = [
'biquad', '{}'.format(b[0]), '{}'.format(b[1]), '{}'.format(b[2]),
'{}'.format(a[0]), '{}'.format(a[1]), '{}'.format(a[2])
]
self.effects.extend(effect_args)
self.effects_log.append('biquad')
return self
def channels(self, n_channels):
'''Change the number of channels in the audio signal. If decreasing the
number of channels it mixes channels together, if increasing the number
of channels it duplicates.
Note: This overrides arguments used in the convert effect!
Parameters
----------
n_channels : int
Desired number of channels.
See Also
--------
convert
'''
if not isinstance(n_channels, int) or n_channels <= 0:
raise ValueError('n_channels must be a positive integer.')
effect_args = ['channels', '{}'.format(n_channels)]
self.effects.extend(effect_args)
self.effects_log.append('channels')
return self
def chorus(self, gain_in=0.5, gain_out=0.9, n_voices=3, delays=None,
decays=None, speeds=None, depths=None, shapes=None):
'''Add a chorus effect to the audio. This can makeasingle vocal sound
like a chorus, but can also be applied to instrumentation.
Chorus resembles an echo effect with a short delay, but whereas with
echo the delay is constant, with chorus, it is varied using sinusoidal
or triangular modulation. The modulation depth defines the range the
modulated delay is played before or after the delay. Hence the delayed
sound will sound slower or faster, that is the delayed sound tuned
around the original one, like in a chorus where some vocals are
slightly off key.
Parameters
----------
gain_in : float, default=0.3
The time in seconds over which the instantaneous level of the input
signal is averaged to determine increases in volume.
gain_out : float, default=0.8
The time in seconds over which the instantaneous level of the input
signal is averaged to determine decreases in volume.
n_voices : int, default=3
The number of voices in the chorus effect.
delays : list of floats > 20 or None, default=None
If a list, the list of delays (in miliseconds) of length n_voices.
If None, the individual delay parameters are chosen automatically
to be between 40 and 60 miliseconds.
decays : list of floats or None, default=None
If a list, the list of decays (as a fraction of gain_in) of length
n_voices.
If None, the individual decay parameters are chosen automatically
to be between 0.3 and 0.4.
speeds : list of floats or None, default=None
If a list, the list of modulation speeds (in Hz) of length n_voices
If None, the individual speed parameters are chosen automatically
to be between 0.25 and 0.4 Hz.
depths : list of floats or None, default=None
If a list, the list of depths (in miliseconds) of length n_voices.
If None, the individual delay parameters are chosen automatically
to be between 1 and 3 miliseconds.
shapes : list of 's' or 't' or None, deault=None
If a list, the list of modulation shapes - 's' for sinusoidal or
't' for triangular - of length n_voices.
If None, the individual shapes are chosen automatically.
'''
if not is_number(gain_in) or gain_in <= 0 or gain_in > 1:
raise ValueError("gain_in must be a number between 0 and 1.")
if not is_number(gain_out) or gain_out <= 0 or gain_out > 1:
raise ValueError("gain_out must be a number between 0 and 1.")
if not isinstance(n_voices, int) or n_voices <= 0:
raise ValueError("n_voices must be a positive integer.")
# validate delays
if not (delays is None or isinstance(delays, list)):
raise ValueError("delays must be a list or None")
if delays is not None:
if len(delays) != n_voices:
raise ValueError("the length of delays must equal n_voices")
if any((not is_number(p) or p < 20) for p in delays):
raise ValueError("the elements of delays must be numbers > 20")
else:
delays = [random.uniform(40, 60) for _ in range(n_voices)]
# validate decays
if not (decays is None or isinstance(decays, list)):
raise ValueError("decays must be a list or None")
if decays is not None:
if len(decays) != n_voices:
raise ValueError("the length of decays must equal n_voices")
if any((not is_number(p) or p <= 0 or p > 1) for p in decays):
raise ValueError(
"the elements of decays must be between 0 and 1"
)
else:
decays = [random.uniform(0.3, 0.4) for _ in range(n_voices)]
# validate speeds
if not (speeds is None or isinstance(speeds, list)):
raise ValueError("speeds must be a list or None")
if speeds is not None:
if len(speeds) != n_voices:
raise ValueError("the length of speeds must equal n_voices")
if any((not is_number(p) or p <= 0) for p in speeds):
raise ValueError("the elements of speeds must be numbers > 0")
else:
speeds = [random.uniform(0.25, 0.4) for _ in range(n_voices)]
# validate depths
if not (depths is None or isinstance(depths, list)):
raise ValueError("depths must be a list or None")
if depths is not None:
if len(depths) != n_voices:
raise ValueError("the length of depths must equal n_voices")
if any((not is_number(p) or p <= 0) for p in depths):
raise ValueError("the elements of depths must be numbers > 0")
else:
depths = [random.uniform(1.0, 3.0) for _ in range(n_voices)]
# validate shapes
if not (shapes is None or isinstance(shapes, list)):
raise ValueError("shapes must be a list or None")
if shapes is not None:
if len(shapes) != n_voices:
raise ValueError("the length of shapes must equal n_voices")
if any((p not in ['t', 's']) for p in shapes):
raise ValueError("the elements of shapes must be 's' or 't'")
else:
shapes = [random.choice(['t', 's']) for _ in range(n_voices)]
effect_args = ['chorus', '{}'.format(gain_in), '{}'.format(gain_out)]
for i in range(n_voices):
effect_args.extend([
'{}'.format(delays[i]),
'{}'.format(decays[i]),
'{}'.format(speeds[i]),
'{}'.format(depths[i]),
'-{}'.format(shapes[i])
])
self.effects.extend(effect_args)
self.effects_log.append('chorus')
return self
def compand(self, attack_time=0.3, decay_time=0.8, soft_knee_db=6.0,
tf_points=[(-70, -70), (-60, -20), (0, 0)]):
'''Compand (compress or expand) the dynamic range of the audio.
Parameters
----------
attack_time : float, default=0.3
The time in seconds over which the instantaneous level of the input
signal is averaged to determine increases in volume.
decay_time : float, default=0.8
The time in seconds over which the instantaneous level of the input
signal is averaged to determine decreases in volume.
soft_knee_db : float or None, default=6.0
The ammount (in dB) for which the points at where adjacent line
segments on the transfer function meet will be rounded.
If None, no soft_knee is applied.
tf_points : list of tuples
Transfer function points as a list of tuples corresponding to
points in (dB, dB) defining the compander's transfer function.
See Also
--------
mcompand, contrast
'''
if not is_number(attack_time) or attack_time <= 0:
raise ValueError("attack_time must be a positive number.")
if not is_number(decay_time) or decay_time <= 0:
raise ValueError("decay_time must be a positive number.")
if attack_time > decay_time:
logging.warning(
"attack_time is larger than decay_time.\n"
"For most situations, attack_time should be shorter than "
"decay time because the human ear is more sensitive to sudden "
"loud music than sudden soft music."
)
if not (is_number(soft_knee_db) or soft_knee_db is None):
raise ValueError("soft_knee_db must be a number or None.")
if not isinstance(tf_points, list):
raise TypeError("tf_points must be a list.")
if len(tf_points) == 0:
raise ValueError("tf_points must have at least one point.")
if any(not isinstance(pair, tuple) for pair in tf_points):
raise ValueError("elements of tf_points must be pairs")
if any(len(pair) != 2 for pair in tf_points):
raise ValueError("Tuples in tf_points must be length 2")
if any(not (is_number(p[0]) and is_number(p[1])) for p in tf_points):
raise ValueError("Tuples in tf_points must be pairs of numbers.")
if any((p[0] > 0 or p[1] > 0) for p in tf_points):
raise ValueError("Tuple values in tf_points must be <= 0 (dB).")
if len(tf_points) > len(set([p[0] for p in tf_points])):
raise ValueError("Found duplicate x-value in tf_points.")
tf_points = sorted(
tf_points,
key=lambda tf_points: tf_points[0]
)
transfer_list = []
for point in tf_points:
transfer_list.extend([
"{}".format(point[0]), "{}".format(point[1])
])
effect_args = [
'compand',
"{},{}".format(attack_time, decay_time)
]
if soft_knee_db is not None:
effect_args.append(
"{}:{}".format(soft_knee_db, ",".join(transfer_list))
)
else:
effect_args.append(",".join(transfer_list))
self.effects.extend(effect_args)
self.effects_log.append('compand')
return self
def contrast(self, amount=75):
'''Comparable with compression, this effect modifies an audio signal to
make it sound louder.
Parameters
----------
amount : float
Amount of enhancement between 0 and 100.
See Also
--------
compand, mcompand
'''
if not is_number(amount) or amount < 0 or amount > 100:
raise ValueError('amount must be a number between 0 and 100.')
effect_args = ['contrast', '{}'.format(amount)]
self.effects.extend(effect_args)
self.effects_log.append('contrast')
return self
def convert(self, samplerate=None, n_channels=None, bitdepth=None):
'''Converts output audio to the specified format.
Parameters
----------
samplerate : float, default=None
Desired samplerate. If None, defaults to the same as input.
n_channels : int, default=None
Desired number of channels. If None, defaults to the same as input.
bitdepth : int, default=None
Desired bitdepth. If None, defaults to the same as input.
See Also
--------
rate
'''
bitdepths = [8, 16, 24, 32, 64]
if bitdepth is not None:
if bitdepth not in bitdepths:
raise ValueError(
"bitdepth must be one of {}.".format(str(bitdepths))
)
self.output_format.extend(['-b', '{}'.format(bitdepth)])
if n_channels is not None:
if not isinstance(n_channels, int) or n_channels <= 0:
raise ValueError(
"n_channels must be a positive integer."
)
self.output_format.extend(['-c', '{}'.format(n_channels)])
if samplerate is not None:
if not is_number(samplerate) or samplerate <= 0:
raise ValueError("samplerate must be a positive number.")
self.rate(samplerate)
return self
def dcshift(self, shift=0.0):
'''Apply a DC shift to the audio.
Parameters
----------
shift : float
Amount to shift audio between -2 and 2. (Audio is between -1 and 1)
See Also
--------
highpass
'''
if not is_number(shift) or shift < -2 or shift > 2:
raise ValueError('shift must be a number between -2 and 2.')
effect_args = ['dcshift', '{}'.format(shift)]
self.effects.extend(effect_args)
self.effects_log.append('dcshift')
return self
def deemph(self):
'''Apply Compact Disc (IEC 60908) de-emphasis (a treble attenuation
shelving filter). Pre-emphasis was applied in the mastering of some
CDs issued in the early 1980s. These included many classical music
albums, as well as now sought-after issues of albums by The Beatles,
Pink Floyd and others. Pre-emphasis should be removed at playback time
by a de-emphasis filter in the playback device. However, not all modern
CD players have this filter, and very few PC CD drives have it; playing
pre-emphasised audio without the correct de-emphasis filter results in
audio that sounds harsh and is far from what its creators intended.
The de-emphasis filter is implemented as a biquad and requires the
input audio sample rate to be either 44.1kHz or 48kHz. Maximum
deviation from the ideal response is only 0.06dB (up to 20kHz).
See Also
--------
bass, treble
'''
effect_args = ['deemph']
self.effects.extend(effect_args)
self.effects_log.append('deemph')
return self
def delay(self, positions):
'''Delay one or more audio channels such that they start at the given
positions.
Parameters
----------
positions: list of floats
List of times (in seconds) to delay each audio channel.
If fewer positions are given than the number of channels, the
remaining channels will be unaffected.
'''
if not isinstance(positions, list):
raise ValueError("positions must be a a list of numbers")
if not all((is_number(p) and p >= 0) for p in positions):
raise ValueError("positions must be positive nubmers")
effect_args = ['delay']
effect_args.extend(['{}'.format(p) for p in positions])
self.effects.extend(effect_args)
self.effects_log.append('delay')
return self
def downsample(self, factor=2):
'''Downsample the signal by an integer factor. Only the first out of
each factor samples is retained, the others are discarded.
No decimation filter is applied. If the input is not a properly
bandlimited baseband signal, aliasing will occur. This may be desirable
e.g., for frequency translation.
For a general resampling effect with anti-aliasing, see rate.