-
Notifications
You must be signed in to change notification settings - Fork 0
/
SoundEffectLib.pyx
6266 lines (4845 loc) · 228 KB
/
SoundEffectLib.pyx
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
# cython: boundscheck=False, wraparound=False, nonecheck=False, optimize.use_switch=True, optimize.unpack_method_calls=True, cdivision=True
# encoding: utf-8
from __future__ import print_function
__author__ = "Yoann Berenguer"
__copyright__ = "Copyright 2021."
__credits__ = ["Yoann Berenguer"]
__license__ = "MIT License"
__version__ = "1.0.1"
__maintainer__ = "Yoann Berenguer"
__email__ = "[email protected]"
__status__ = "tested"
"""
MIT License
Copyright (c) 2019 Yoann Berenguer
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Sound Effect Library is a free software that include a large variety of tools to modify
and create sound effects for video games and can also be used for sound processing.
It provides fast algorithms written in python and Cython in addition to C/C++ code (external libraries)
included with the project.
This project rely on Pygame mixer and sndarray modules in order to build and extract data samples into numpy.sndarray.
The algorithms are build for int16 and float32 array datatype and for monophonic & stereophonic sound effects
Choose the correct algorithm according to the data-type and sound model
Below details list of methods available at your convenience
- Microphone recording
- Sound recording (wav format)
- Data sample normalisation &reverse normalisation process
- RMS calculator and display
- Fade in / Fade out effect
- Tinnitus effect
- Generate silence
- Low pass filter
- Harmonic representation
- Noise signal
- Square signal
- triangular signal
- cosine signal
- Cosine carrier
- Sound time shifting
- Volume change
- Reverse sound
- Sound Inversion
- Mixing sounds
- Up / Down data sampling
- Panning sound effect
- Median filtering
- Averaging filtering
- Echo sound effect
- Pitch shifting and time stretching
Not included in this version
- Gaussian filtering
pip install pygame cython numpy librosa pyaudio matplotlib scipy wave pandas
- setuptools>=49.2.1
- pygame>=1.9.6
- Cython>=0.28
- numpy~=1.18.0
- matplotlib~=2.2.2
- scipy~=1.1.0
- Wave~=0.0.2
- PyAudio~=0.2.11
- pandas~=0.22.0
- librosa>=0.8.0
- A compiler such visual studio, MSVC, CGYWIN setup correctly
on your system.
- a C compiler for windows (Visual Studio, MinGW etc) install on your system
and linked to your windows environment.
Note that some adjustment might be needed once a compiler is install on your system,
refer to external documentation or tutorial in order to setup this process.
e.g https://devblogs.microsoft.com/python/unable-to-find-vcvarsall-bat/
# In a command prompt and under the directory containing the source files
C:\>python setup_project.py build_ext --inplace
...
...
...
Creating library build\temp.win-amd64-3.6\Release\SoundEffectLib.cp36-win_amd64.lib and object
build\temp.win-amd64-3.6\Release\SoundEffectLib.cp36-win_amd64.exp
Generating code
Finished generating code
# If the compilation fail, refers to the requirement section and make sure cython
# and a C-compiler are correctly install on your system.
"""
"""
FLAG USED
@cython.optimize.unpack_method_calls(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
@cython.optimize.use_switch(False)
"""
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=ImportWarning)
try:
import pyaudio
except ImportError:
raise ImportError("\n<pyaudio> library is missing on your system."
"\nTry: \n C:\\pip install pygame on a window command prompt.")
from pyaudio import paFloat32, paInt32, paInt24, paInt16, paInt8, paUInt8
try:
import librosa
except ImportError:
raise ImportError("\n<librosa> library is missing on your system."
"\nTry: \n C:\\pip install librosa on a window command prompt.")
try:
import pygame
except ImportError:
raise ImportError("\n<pygame> library is missing on your system."
"\nTry: \n C:\\pip install pygame on a window command prompt.")
from pygame import sndarray
from pygame.sndarray import make_sound
from libc.stdio cimport printf
from libc.math cimport sqrt, cos, sin, log10, fabs, atan, atan2
from libc.stdlib cimport abs
from libc.limits cimport SHRT_MIN, SHRT_MAX
from libc.stdlib cimport malloc
try:
cimport cython
except ImportError:
raise ImportError("\n<cython> library is missing on your system."
"\nTry: \n C:\\pip install cython on a window command prompt.")
# from cpython.list cimport PyList_Append, PyList_GetItem, PyList_Size, PyList_SetItem, PyList_SET_ITEM
# from cpython.object cimport PyObject_SetAttr
# from cpython.dict cimport PyDict_SetItem
from cpython cimport PyObject_HasAttr, PyObject_IsInstance
# from cpython cimport array
from cython.parallel cimport prange
try:
import numpy as numpy
except ImportError:
raise ImportError("\n<numpy> library is missing on your system."
"\nTry: \n C:\\pip install numpy on a window command prompt.")
from numpy import zeros, int16, empty, asarray, float32, float64, float_, \
average, amin, amax, round, fft, hanning, ascontiguousarray
cimport numpy
from numpy cimport uint8_t, int16_t, float32_t, complex_t, float64_t
try:
from scipy import signal
except ImportError:
raise ImportError("\n<scipy> library is missing on your system."
"\nTry: \n C:\\pip install scipy on a window command prompt.")
from ErrorMsg_uk import *
try:
import matplotlib.pyplot as plt
except ImportError:
raise ImportError("\n<matplotlib> library is missing on your system."
"\nTry: \n C:\\pip install matplotlib on a window command prompt.")
import logging
cdef extern from 'QuickSort.c' nogil:
int * quickSort(int arr[], int low, int high)nogil
float f_max(float arr[], int element)nogil
cdef extern from 'randnumber.c':
void init_clock()nogil
float randRangeFloat(float lower, float upper)nogil
int randRange(int lower, int upper)nogil
cdef extern from 'PitchShifting.cpp':
void smbPitchShift(float pitchShift, long numSampsToProcess, long fftFrameSize,
long osamp, float sampleRate, float *indata, float *outdata)nogil
DEF SCHEDULE = 'static'
DEF OPENMP = True
# num_threads – The num_threads argument indicates how many threads the team should consist of.
# If not given, OpenMP will decide how many threads to use.
# Typically this is the number of cores available on the machine. However,
# this may be controlled through the omp_set_num_threads() function,
# or through the OMP_NUM_THREADS environment variable.
if OPENMP is True:
DEF THREAD_NUMBER = 8
else:
DEF THREAD_NUMBER = 1
DEF PI = 3.14159265359
DEF PI2 = 2 * PI
DEF DEG_TO_RADIAN = PI / 180.0
DEF RADIAN_TO_DEG = 180.0 / PI
cdef:
float INV_SHRT_MAX = 1.0 / SHRT_MAX
float INV_SHRT_MIN = 1.0 / SHRT_MIN
# Sample rate allowed
FS = [8000, 11025, 16000, 22050, 32000, 44100, 48000,
88200, 96000, 176400, 192000, 352800, 384400]
PYAUDIO_FORMAT = [paFloat32, paInt32, paInt24, paInt16, paInt8, paUInt8]
SOUNDTYPE = pygame.mixer.Sound
cdef struct rms:
double s0
double s1
ctypedef rms RMS
init_clock()
try:
import wave
except ImportError:
raise ImportError("\n<wave> library is missing on your system."
"\nTry: \n C:\\pip install wave on a window command prompt.")
import os
PATH = os.getcwd()
# todo profiling
cpdef record_microphone(int format_=paInt16,
short int channels_=1,
int sample_rate_=44100,
int chunk_=16384,
int duration_=10,
bint record_=False,
str filename_="output.wav"):
"""
RECORD SOUNDS FROM THE MICROPHONE
Return OSError if no microphone can be used for recording.
OSError: [Errno -9996] Invalid input device (no default output device)
:param format_ : integer; Audio format paFloat32, paInt32, paInt24, paInt16, paInt8, paUInt8
:param channels_ : integer; number of channels must be 1 or 2
:param sample_rate_: integer; sample rate must be in 8000, 11025, 16000, 22050, 32000, 44100, 48000,
88200, 96000, 176400, 192000, 352800, 384400
:param chunk_ : integer; Specifies the number of frames per buffer (default 16384)
:param duration_ : integer; Record duration, default 1 seconds
:param record_ : bool; True | False. If true the record will be save onto a file (default : output.wav)
:param filename_ : string; Record name (only when record is True)
:return: Return a buffer type unsigned char shape (n,)
"""
if chunk_ == 0:
raise ValueError("\nArgument chunk_ cannot be equal zero!")
if chunk_<1024:
raise ValueError(message35 % ("chunk_", 1024, chunk_) )
if not format_ in PYAUDIO_FORMAT:
raise ValueError("\nUnknown format %s, accept %s " % (format_, PYAUDIO_FORMAT))
if channels_:
if channels_ not in (1, 2):
raise ValueError(message7)
if sample_rate_ not in FS:
raise ValueError(message15 % (sample_rate_, FS))
if duration_ <= 0:
raise ValueError(message35 % ("duration_", 1, duration_))
name, extension = filename_.split(".")
if len(extension) != 3:
raise ValueError(message33)
if extension.upper() != 'WAV':
raise ValueError(message32 % extension)
p = pyaudio.PyAudio()
stream = p.open(format=format_,
channels=channels_,
rate=sample_rate_,
input=True,
frames_per_buffer=chunk_)
print("* recording *")
frames = []
try:
for _ in range(0, int(duration_ * sample_rate_ / chunk_)):
frames.append(stream.read(chunk_))
except Exception as e:
logging.error(message36 % e)
# Concatenate any number of bytes objects.
frames_array = numpy.frombuffer(b''.join(frames), dtype=float32)
print("* done recording *")
stream.stop_stream()
stream.close()
if record_:
try:
wf = wave.open(filename_, 'wb')
wf.setnchannels(channels_)
wf.setsampwidth(p.get_sample_size(format_))
wf.setframerate(sample_rate_)
wf.writeframes(frames_array)
wf.close()
except Exception as e:
logging.error(message37 % e)
# Close the file
if "wf" in globals():
if wf is not None and hasattr(wf, "close"):
try:
wf.close()
except OSError as e:
logging.error(message38 % e)
return
p.terminate()
return frames_array
# todo profiling
cpdef record_sound(sound_, str filename_):
"""
SAVE A SOUND OBJECT ON DISK (INPUT CAN BE A NUMPY ARRAY OR A SOUND OBJECT)
* input can be a pygame.mixer.sound object or a numpy array (monophonic or stereophonic)
* compatible with stereophonic or monophonic sounds
:param sound_: pygame.mixer.sound; Sound object to save onto disk
:param filename_: string; filename including file extension (this method is only compatible with wav file)
:return: boolean; True | False if the sound has been successfully saved
"""
if not is_type_soundobject(sound_):
# Convert array into a sound object
try:
sound_ = pygame.sndarray.make_sound(sound_)
except:
raise ValueError(message30)
mixer_settings = pygame.mixer.get_init()
if mixer_settings is None:
raise ValueError(message6)
if not os.path.exists(PATH):
raise ValueError()
name, extension = filename_.split(".")
if len(extension) != 3:
raise ValueError(message33)
if extension.upper() != 'WAV':
raise ValueError(message32 % extension)
try:
destination_file = wave.open(os.path.join(PATH, filename_), 'w')
# set the parameters
destination_file.setframerate(mixer_settings[0]) # frequency
destination_file.setnchannels(mixer_settings[2]) # channel(s)
destination_file.setsampwidth(2)
# write raw PyGame sound buffer to wave file
destination_file.writeframesraw(sound_.get_raw())
destination_file.close()
return True
except Exception as e:
logging.error(message37 % e)
# Close the file
if "destination_file" in globals():
if destination_file is not None and hasattr(destination_file, "close"):
try:
destination_file.close()
except OSError as e:
logging.error(message38 % e)
return False
cpdef normalize_array_mono(short [:] samples):
"""
TAKE A NUMPY.NDARRAY AS INPUT (TYPE INT16) AND NORMALIZED THE VALUES (FLOAT32)
:param samples: numpy.ndarray; Python numpy.ndarray type int16 representing the sound samples
:return : a memoryview of an numpy.ndarray, with values [-1.0 pass +1.0] type python float (cython.double).
Contiguous array
"""
if not is_valid_mono_array(samples):
raise ValueError(message11)
cdef:
int width = <object>samples.shape[0]
float [::1] new_array = empty(width, float32)
int i
float s0
if width == 0:
raise ValueError(message12)
with nogil:
for i in prange(width, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
s0 = samples[i]
if s0 > 0:
new_array[i] = s0 * INV_SHRT_MAX
elif s0 < 0:
new_array[i] = -s0 * INV_SHRT_MIN
else:
new_array[i] = 0.0
return new_array
cpdef float [:, :] normalize_array_stereo(short [:, :] samples_):
"""
TAKE AN ARRAY INT16 AS INPUT (SOUND SAMPLES) AND RETURN A NORMALIZED SAMPLES (FLOAT32)
:param samples_: ndarray; reference Sound samples into an array
:return : memoryview type [:, :] with floats values representing a normalized sound
"""
if not is_valid_stereo_array(samples_):
raise ValueError(message14)
cdef:
int width = <object>samples_.shape[0]
int i
float s0, s1
float [:, :] new_array = empty((width, 2), float32)
if width == 0:
raise ValueError(message12)
with nogil:
for i in prange(width, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
s0 = samples_[i, 0]
s1 = samples_[i, 1]
if s0 > 0:
new_array[i, 0] = s0 * INV_SHRT_MAX
elif s0 < 0:
new_array[i, 0] = -s0 * INV_SHRT_MIN
else:
new_array[i, 0] = 0.0
if s1 > 0:
new_array[i, 1] = s1 * INV_SHRT_MAX
elif s1 < 0:
new_array[i, 1] = -s1 * INV_SHRT_MIN
else:
new_array[i, 1] = 0.0
return new_array
cpdef normalize_sound(sound_):
"""
NORMALIZE A PYGAME SOUND OBJECT (STEREO OR MONOPHONIC), RETURN A NUMPY ARRAY
:param sound_: pygame.Sound; Pygame stereo sound object
:return : Return a sndarray python array type (n, ) or (n, 2) object representing
a sound with float values [ -1.0 pass +1.0 ]
"""
if not is_type_soundobject(sound_):
raise ValueError(message23 % 1)
try:
sound_array = pygame.sndarray.samples(sound_)
except:
raise ValueError(message39)
# mono array
if is_valid_mono_array(sound_array):
# Array is already normalized
if sound_array.dtype == float32:
return sound_array
# stereo array
elif is_valid_stereo_array(sound_array):
# Array is already normalized (float32)
if sound_array.dtype==float32:
return sound_array
else:
raise ValueError(message30)
cdef:
int channel_number = len(sound_array.shape)
int width = <object>sound_array.shape[0]
short [::1] array_mono = sound_array if channel_number == 1 else empty(width, int16)
short [:, :] array_stereo = sound_array if channel_number == 2 else empty((width, 2), int16)
float [:, :] stereo_samples = empty((width, 2), float32)
float [::1] mono_sample = empty(width, float32)
int i
float s0, s1
if width == 0:
raise ValueError(message12)
# stereo
if channel_number == 2:
with nogil:
for i in prange(width, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
s0 = array_stereo[i, 0]
s1 = array_stereo[i, 1]
if s0 > 0:
stereo_samples[i, 0] = <float>(s0 * INV_SHRT_MAX)
elif s0 < 0:
stereo_samples[i, 0] = <float>(-s0 * INV_SHRT_MIN)
else:
stereo_samples[i, 0] = 0.0
if s1 > 0:
stereo_samples[i, 1] = <float>(s1 * INV_SHRT_MAX)
elif s1 < 0:
stereo_samples[i, 1] = <float>(-s1 * INV_SHRT_MIN)
else:
stereo_samples[i, 1] = 0.0
return asarray(stereo_samples)
# mono
elif channel_number == 1:
with nogil:
for i in prange(width, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
s0 = array_mono[i]
if s0 > 0:
mono_sample[i] = <float>(s0 * INV_SHRT_MAX)
elif s0 < 0:
mono_sample[i] = <float>(-s0 * INV_SHRT_MIN)
else:
mono_sample[i] = 0.0
return asarray(mono_sample)
else:
raise ValueError(message30)
# **************************** FADE-IN *************************************
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
@cython.optimize.use_switch(False)
cpdef fade_in(sound_, float fade_in_, float sample_rate_):
"""
FADE IN EFFECT (INPLACE)
* Compatible monophonic and stereophonic sound effect
:param sound_ : pygame Sound; Sound to fade-in (Monophonic or stereophonic)
:param fade_in_ : float; end of the fade in effect (in seconds). Cannot exceed the sound duration.
:param sample_rate_: float; Sample rate
:return : Void; change inplace
"""
if not is_type_soundobject(sound_):
raise ValueError(message23 % sound_)
try:
sound_array = pygame.sndarray.samples(sound_)
except:
raise ValueError(message39 % "sound_")
if sample_rate_ not in FS:
raise ValueError(message15 % (sample_rate_, FS))
cdef:
int width = <object>sound_array.shape[0]
float t = <float>width / <float>sample_rate_
if width == 0:
raise ValueError(message12)
if fade_in_ == 0:
return
elif fade_in_ < 0:
raise ValueError(message24 % "fade_in_")
elif fade_in_ > t:
raise ValueError(message25 % ("fade_in_", t, fade_in_))
if sound_array.dtype == float32:
if is_valid_mono_array(sound_array):
sound_array = fade_in_mono_float32(sound_array, fade_in_, sample_rate_)
elif is_valid_stereo_array(sound_array):
sound_array = fade_in_stereo_float32(sound_array, fade_in_, sample_rate_)
else:
raise ValueError(message30)
elif sound_array.dtype == int16:
if is_valid_mono_array(sound_array):
sound_array = fade_in_mono_int16(sound_array, fade_in_, sample_rate_)
elif is_valid_stereo_array(sound_array):
sound_array = fade_in_stereo_int16(sound_array, fade_in_, sample_rate_)
else:
raise ValueError(message30)
else:
raise ValueError(message27 % sound_array.dtype)
@cython.optimize.unpack_method_calls(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
@cython.optimize.use_switch(False)
cpdef fade_in_mono_int16(short [::1] samples_, const float fade_in_, const float sample_rate_):
"""
FADE IN FOR MONOPHONIC SOUND (INT16)
These basic fades apply a fade to the selected audio such that the amplitude
of the selection goes from absolute silence to the original amplitude (fade in).
the shape of the fade is linear, so it appears as a straight line from beginning
to end. The speed of the fade in or out is therefore constant throughout its length
and depends entirely on the length selected for the fade.
* Compatible with monophonic sound object only
* Return a numpy.array shape (n, ) int16 with fade in effect
:param samples_ : ndarray; Reference Sound samples into an array. numpy.ndarray int16
(contiguous array) shape (n, )
:param fade_in_ : float; fade_in_, end of the fade in effect (in seconds). Cannot exceed the sound duration.
:param sample_rate_ : float; Sample rate
:return : Return a numpy.array contiguous shape (n, ) int16 with fade in effect
"""
if not is_valid_mono_array(samples_):
raise ValueError(message11)
if sample_rate_ not in FS:
raise ValueError(message15 % (sample_rate_, FS))
cdef:
int width = <object>samples_.shape[0]
float t = <float>width / <float>sample_rate_
if width == 0:
raise ValueError(message12)
if fade_in_ == 0:
return asarray(samples_, int16)
elif fade_in_ < 0:
raise ValueError(message24 % "fade_in_")
elif fade_in_ > t:
raise ValueError(message25 % ("fade_in_", t, fade_in_))
cdef:
int i = 0
float time_pos
int end = <int>(fade_in_ * sample_rate_)
with nogil:
for i in prange(0, end, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
time_pos = 1 - <float>(end - i) / <float>end
samples_[i] = <short>(samples_[i] * time_pos)
return asarray(samples_)
@cython.optimize.unpack_method_calls(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
@cython.optimize.use_switch(False)
cpdef fade_in_mono_float32(float [::1] samples_, const float fade_in_, const float sample_rate_):
"""
FADE IN FOR MONOPHONIC SOUND (FLOAT32)
These basic fades apply a fade to the selected audio such that the amplitude
of the selection goes from absolute silence to the original amplitude (fade in).
the shape of the fade is linear, so it appears as a straight line from beginning
to end. The speed of the fade in or out is therefore constant throughout its length
and depends entirely on the length selected for the fade.
* Compatible with monophonic sound object only
* Return a numpy.array shape (n, ) float32 with fade in effect
:param samples_ : ndarray; Reference Sound samples into an array. numpy.ndarray float32
(contiguous array) shape (n, )
:param fade_in_ : float; fade_in_, end of the fade in effect (in seconds). Cannot exceed the sound duration.
:param sample_rate_ : float; Sample rate
:return : Return a numpy.array contiguous shape (n, ) float32 with fade in effect
"""
if not is_valid_mono_array(samples_):
raise ValueError(message11)
if sample_rate_ not in FS:
raise ValueError(message15 % (sample_rate_, FS))
cdef:
int width = <object>samples_.shape[0]
float t = <float>width / <float>sample_rate_
if width == 0:
raise ValueError(message12)
if fade_in_ == 0:
return asarray(samples_, float32)
elif fade_in_ < 0:
raise ValueError(message24 % "fade_in_")
elif fade_in_ > t:
raise ValueError(message25 % ("fade_in_", t, fade_in_))
cdef:
int i = 0
float time_pos
int end = <int>(fade_in_ * sample_rate_)
with nogil:
for i in prange(0, end, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
time_pos = 1 - <float>(end - i) / <float>end
samples_[i] = <float>(samples_[i] * time_pos)
return asarray(samples_, float32)
@cython.optimize.unpack_method_calls(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
@cython.optimize.use_switch(False)
cpdef fade_in_stereo_int16(short [:, :] samples_, const float fade_in_, const float sample_rate_):
"""
FADE IN STEREOPHONIC SOUNDS (INT16)
These basic fades apply a fade to the selected audio such that the amplitude
of the selection goes from absolute silence to the original amplitude (fade in).
the shape of the fade is linear, so it appears as a straight line from beginning
to end. The speed of the fade in or out is therefore constant throughout its length
and depends entirely on the length selected for the fade.
* Compatible with stereophonic sound object only
* Return a numpy.array shape (n, ) int16 with fade in effect
:param samples_ : ndarray; Reference Sound samples into an array. Numpy ndarray shape (n, 2) int16
:param fade_in_ : float; fade_in_, end of the fade in effect (in seconds). Cannot exceed the sound duration.
:param sample_rate_ : float; Sample rate
:return : Return a numpy.array stereophonic shape (n , 2) int16
"""
if not is_valid_stereo_array(samples_):
raise ValueError(message14)
if sample_rate_ not in FS:
raise ValueError(message15 % (sample_rate_, FS))
cdef:
int width = <object>samples_.shape[0]
float t = <float>width / <float>sample_rate_
if width == 0:
raise ValueError(message12)
if fade_in_ == 0:
return asarray(samples_)
elif fade_in_ < 0:
raise ValueError(message24 % "fade_in_")
elif fade_in_ > t:
raise ValueError(message25 % ("fade_in_", t, fade_in_))
cdef:
int i = 0
float time_pos
int end = <int>(fade_in_ * sample_rate_)
with nogil:
for i in prange(0, end, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
time_pos = 1 - <float>(end - i) / <float>end
samples_[i, 0] = <short>(samples_[i, 0] * time_pos)
samples_[i, 1] = <short>(samples_[i, 1] * time_pos)
return asarray(samples_, int16)
@cython.optimize.unpack_method_calls(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
@cython.optimize.use_switch(False)
cpdef fade_in_stereo_float32(float [:, :] samples_, const float fade_in_, const float sample_rate_):
"""
FADE IN STEREOPHONIC SOUNDS (FLOAT32)
These basic fades apply a fade to the selected audio such that the amplitude
of the selection goes from absolute silence to the original amplitude (fade in).
the shape of the fade is linear, so it appears as a straight line from beginning
to end. The speed of the fade in or out is therefore constant throughout its length
and depends entirely on the length selected for the fade.
* Compatible with stereophonic sound object only
* Return a numpy.array shape (n, ) float32 with fade in effect
:param samples_ : ndarray; Reference Sound samples into an array. Numpy ndarray shape (n, 2) float32
:param fade_in_ : float; fade_in_, end of the fade in effect (in seconds). Cannot exceed the sound duration.
:param sample_rate_ : float; Sample rate
:return : Return a numpy.array stereophonic shape (n , 2) float32
"""
if not is_valid_stereo_array(samples_):
raise ValueError(message14)
if sample_rate_ not in FS:
raise ValueError(message15 % (sample_rate_, FS))
cdef:
int width = <object>samples_.shape[0]
float t = <float>width / <float>sample_rate_
if width == 0:
raise ValueError(message12)
if fade_in_ == 0:
return asarray(samples_, float32)
elif fade_in_ < 0:
raise ValueError(message24 % "fade_in_")
elif fade_in_ > t:
raise ValueError(message25 % ("fade_in_", t, fade_in_))
cdef:
int i = 0
float time_pos
int end = <int>(fade_in_ * sample_rate_)
with nogil:
for i in prange(0, end, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
time_pos = 1 - <float>(end - i) / <float>end
samples_[i, 0] = <float>(samples_[i, 0] * time_pos)
samples_[i, 1] = <float>(samples_[i, 1] * time_pos)
return asarray(samples_, float32)
@cython.optimize.unpack_method_calls(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
@cython.optimize.use_switch(False)
cpdef fade_in_mono_inplace_int16(short [::1] samples_, const float fade_in_, const float sample_rate_):
"""
FADE IN FOR MONOPHONIC SOUND (INT16) INPLACE
These basic fades apply a fade to the selected audio such that the amplitude
of the selection goes from absolute silence to the original amplitude (fade in)
or from the original amplitude to absolute silence (fade out).
the shape of the fade is linear, so it appears as a straight line from beginning
to ens. The speed of the fade in or out is therefore constant throughout its length
and depends entirely on the length selected for the fade.
* Compatible with monophonic sound object only
:param samples_ : ndarray; Reference Sound samples into an array. Numpy.array shape (n, ) monophonic int16
:param fade_in_ : float; fade_in_, end of the fade in effect (in seconds). Cannot exceed the sound duration.
:param sample_rate_ : float; Sample rate
:return : Void
"""
if not is_valid_mono_array(samples_):
raise ValueError(message11)
if sample_rate_ not in FS:
raise ValueError(message15 % (sample_rate_, FS))
cdef:
int width = <object>samples_.shape[0]
float t = <float>width / <float>sample_rate_
if width == 0:
raise ValueError(message12)
if fade_in_ == 0:
return asarray(samples_)
elif fade_in_ < 0:
raise ValueError(message24 % "fade_in_")
elif fade_in_ > t:
raise ValueError(message25 % ("fade_in_", t, fade_in_))
cdef:
int i = 0
float time_pos
int end = <int>(fade_in_ * sample_rate_)
with nogil:
for i in prange(0, end, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
time_pos = 1 - <float>(end - i) / <float>end
samples_[i] = <short>(samples_[i] * time_pos)
@cython.optimize.unpack_method_calls(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
@cython.optimize.use_switch(False)
cpdef fade_in_mono_inplace_float32(float [::1] samples_, const float fade_in_, const float sample_rate_):
"""
FADE IN FOR MONOPHONIC SOUND (float32) INPLACE
These basic fades apply a fade to the selected audio such that the amplitude
of the selection goes from absolute silence to the original amplitude (fade in)
or from the original amplitude to absolute silence (fade out).
the shape of the fade is linear, so it appears as a straight line from beginning
to ens. The speed of the fade in or out is therefore constant throughout its length
and depends entirely on the length selected for the fade.
* Compatible with monophonic sound object only
:param samples_ : ndarray; Reference Sound samples into an array. Numpy.array shape (n, ) monophonic float32
:param fade_in_ : float; fade_in_, end of the fade in effect (in seconds). Cannot exceed the sound duration.
:param sample_rate_ : float; Sample rate
:return : Void
"""
if not is_valid_mono_array(samples_):
raise ValueError(message11)
if sample_rate_ not in FS:
raise ValueError(message15 % (sample_rate_, FS))
cdef:
int width = <object>samples_.shape[0]
float t = <float>width / <float>sample_rate_
if width == 0:
raise ValueError(message12)
if fade_in_ == 0:
return asarray(samples_, float32)
elif fade_in_ < 0:
raise ValueError(message24 % "fade_in_")
elif fade_in_ > t:
raise ValueError(message25 % ("fade_in_", t, fade_in_))
cdef:
int i = 0
float time_pos
int end = <int>(fade_in_ * sample_rate_)
with nogil:
for i in prange(0, end, schedule=SCHEDULE, num_threads=THREAD_NUMBER):
time_pos = 1 - <float>(end - i) / <float>end
samples_[i] = <float>(samples_[i] * time_pos)
@cython.optimize.unpack_method_calls(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
@cython.optimize.use_switch(False)
cpdef fade_in_stereo_inplace_int16(short [:, :] samples_, const float fade_in_, const float sample_rate_):
"""
FADE IN FOR STEREOPHONIC SOUND (INT16) INPLACE