Last active
May 24, 2020 04:46
-
-
Save NP-chaonay/1465cac5046c3e4dcfbd1624e203bce4 to your computer and use it in GitHub Desktop.
My DSP (Audio) code snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Create sine wave and write to disk ### | |
import math | |
import numpy as np | |
import scipy.io.wavfile as scp_io_wav | |
rate=44100 | |
freq=440 | |
sample_num=rate*5 | |
# Note: round to 15 due to inaccurate of resulted value when input values "pi" and "2pi" | |
# Note: Using modulus (When at least 1 cycle of circle sine is reached, reset to 0) to prevent bigger value cause the inaccurate of resulted value. (Using lower rounding decimal point may decrease precision when inputted value goes higher.) | |
array=np.array([round(math.sin((n%2)*math.pi),15) for n in np.linspace(0,2*freq*(sample_num/rate),sample_num)]) | |
to_write_array=np.round(32767*array).astype('int16') | |
scp_io_wav.write('/tmp/wave.wav',rate,to_write_array) | |
### Create sine wave by human-hearable musicial notes and write to disk ### | |
import math | |
import numpy as np | |
import scipy.io.wavfile as scp_io_wav | |
rate=44100 | |
sample_num=rate//2 | |
freqs=[440*2**(n/12) for n in range(-53,67)] | |
accumerated_arr=[] | |
for freq in freqs: | |
# Note: round to 15 due to inaccurate of resulted value when input values "pi" and "2pi" | |
# Note: Using modulus (When at least 1 cycle of circle sine is reached, reset to 0) to prevent bigger value cause the inaccurate of resulted value. (Using lower rounding decimal point may decrease precision when inputted value goes higher.) | |
array=np.array([round(math.sin((n%2)*math.pi),15) for n in np.linspace(0,2*freq*(sample_num/rate),sample_num)]) | |
accumerated_arr+=[array] | |
accumerated_arr=np.concatenate(accumerated_arr) | |
to_write_array=np.round(32767*accumerated_arr).astype('int16') | |
scp_io_wav.write('/tmp/wave.wav',rate,to_write_array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment