import numpy as np
import pandas as pd
import time
import matplotlib.pyplot as plt
from scipy.io.wavfile import write
from scipy.io.wavfile import read
from scipy.fft import fft,fftfreq,ifft
from scipy.signal import correlate
import vlc
# python -m pip install python-vlc
# download: https://www.videolan.org/vlc/download-macosx.htmlSound data demonstration
Python
Import
Parameters
#INPUT PARAM
R=44100 #44.1kHz=standard sampling rate for audio
#MIDDLE FREQUENCIES FOR NOTES ON PIANO
#https://pages.mtu.edu/~suits/notefreqs.html
F_A=220.000
F_B=246.940
F_C=261.626
F_D=293.665
F_E=329.628
F_F=349.230
F_G=391.995
# A=10 # amplitude Utility functions
import math
import numpy as np
import matplotlib.pyplot as plt
#FUNCTION TO BUILD MESH BASED ON FREQUENCIES
def construct_mesh(F):
global T,t,dt
num_cycle=int(2.*F)
T = num_cycle/F #total length of sound in seconds
t = np.linspace(0,T,int(R*T))
t = t[0:-1]
dt= t[1]-t[0]; #TIMESTEP (seconds)
#VISUALIZE WAVEFORM
def visualize_wave(T=-1):
#SHOW INITIAL PART OF WAVEFORM
ax = plt.subplot()
ax.plot(t[0:int(T)], s[0:int(T)], 'b-')
#AXIS LABELS
ax.set_xlabel('time (seconds)')
ax.set_ylabel('s(t)')
plt.show()
def play_waveform(sf=1):
# NORMALIZE (PREVENT SPEAKER DAMAGE)
sn=sf*s/max(s)
#SAVE TO MP3 THEN PLAY
write('output.mp3', R, sn)
p = vlc.MediaPlayer("output.mp3")
p.play(); time.sleep(T);
p.stop()
def spectral_analysis():
N=len(s); #NUMBER OF POINTS
fn=fftfreq(N)/(dt) #SET OF FREQ FOR PLOTTING (Hz)
ts=0 #int(len(fn)/2)
tf=-1 #int(0.6*len(fn))
# FOURIER TRANSFORM
FT=fft(s)
# EXTRACT SIN AND COS AMPLITUDES
# (FACTOR OF 2 IS FOR CONVERSION FROM REAL TO COMPLEX)
# sum(an*cos(wt)+bn*sin(wt))
an=2*np.real(FT)/N
bn=-2*np.imag(FT)/N
SPD=np.absolute(FT)**2.0
# PLOT SIN/COS AMPLITUDES
plt.plot(fn[ts:tf],an[ts:tf], '-o'); plt.show()
plt.plot(fn[ts:tf],bn[ts:tf], '-o'); plt.show()
#SPECTRAL POWER DENSITY
#(FACTOR OF 4 IS FOR CONVERSION FROM REAL TO COMPLEX)
#N SQUARE IS FOR SCIPY NORMALIZATION CONVENTION
plt.plot(fn,4*SPD/N/N,'-o'); plt.show()
#INVERSE TRANSFORM (CONVERT BACK TO ORIGINAL SIGNAL)
s2=ifft(FT)
plt.plot(t[0:100], s2[0:100], 'ro')
plt.plot(t[0:100], s[0:100], 'b-')
plt.show()
print(s.shape)
# Matplotlib.pyplot.specgram() function to
# generate spectrogram
plt.specgram(s, Fs=6, cmap="rainbow")
# Set the title of the plot, xlabel and ylabel
# and display using show() function
plt.title('Spectrogram Using matplotlib.pyplot.specgram() Method')
plt.xlabel("DATA")
plt.ylabel("TIME")
plt.show()Sounds data example:
Base tones and chords
#MIDDLE C: 261.625565 hertz
construct_mesh(F_C)
s = 2*np.sin(2*np.pi*F_C*t)
# s=s-np.mean(s) #SUBTRACT OUT MEAN
visualize_wave(T=int(4*1/F_C/dt))
# visualize_wave(T=-1)
play_waveform(sf=0.5)
spectral_analysis()/Users/jameshickman/miniconda3/envs/anly503/lib/python3.10/site-packages/matplotlib/cbook/__init__.py:1369: ComplexWarning: Casting complex values to real discards the imaginary part
return np.asarray(x, float)
(88156,)
#G=391.995 hertz
f=F_G
construct_mesh(f)
s = 1*np.sin(2*np.pi*f*t)
s=s-np.mean(s) #SUBTRACT OUT MEAN
visualize_wave(T=int(4*1/f/dt))
visualize_wave(T=-1)
play_waveform(sf=1.0)# F CHORD F, A, and C (NO GAUSSIAN PACKET)
construct_mesh(F_A)
s = 5*np.sin(2*3.1415*F_F*t)+3*np.sin(2*3.1415*F_A*t)+7*np.sin(2*3.1415*F_C*t)
# s=s*np.exp(-0.5*((t-0.5*T)/(0.15*T))**2.0)
# s=s-np.mean(s) #SUBTRACT OUT MEAN
visualize_wave()
play_waveform(sf=1.0)# F CHORD: F, A, and C (GAUSSIAN PACKET)
construct_mesh(F_A)
s =10*(np.sin(2*3.1415*F_F*t)+np.sin(2*3.1415*F_A*t)+np.sin(2*3.1415*F_C*t))
s=s*np.exp(-0.5*((t-0.5*T)/(0.15*T))**2.0)
# s=s-np.mean(s) #SUBTRACT OUT MEAN
visualize_wave()
play_waveform(sf=2.0)# #G CHORD: G B and D.
construct_mesh(F_B)
s = 0.33*(np.sin(2*3.1415*F_G*t)+np.sin(2*3.1415*F_B*t)+np.sin(2*3.1415*F_D*t))
visualize_wave()
play_waveform(sf=2.0)# #WHITE NOISE
construct_mesh(F_C)
s = 0.1*np.random.uniform(-1,1,int(44100*T)) # 44100 random samples between -1 and 1
s = 0.1*np.random.normal(0,1,int(44100*T)) # 44100 random samples between -1 and 1
s = s[0:-1]
visualize_wave(T=500)
visualize_wave(T=-1)
play_waveform(sf=1)Sounds data example:
Speech
in_put = read("voice.wav")
# #DEFINE ARRAYS
R=in_put[0] #SAMPLE RATE
s=in_put[1] #ARRAY
T=len(s)/R
t=np.linspace(0,T,int(R*T)); print(t.shape,s.shape)
dt= t[1]-t[0]; #TIMESTEP (seconds)
visualize_wave(T=R)
visualize_wave(T=-1)
play_waveform(sf=1)
spectral_analysis()(219136,) (219136,)
(219136,)
/Users/jameshickman/miniconda3/envs/anly503/lib/python3.10/site-packages/matplotlib/axes/_axes.py:7720: RuntimeWarning: divide by zero encountered in log10
Z = 10. * np.log10(spec)
play_waveform(sf=1)Sounds data example:
Music-1
in_put = read("jamming-1.wav")
# #DEFINE ARRAYS
R=in_put[0] #SAMPLE RATE
s=in_put[1] #ARRAY
T=len(s)/R
t=np.linspace(0,T,int(R*T)); print(t.shape,s.shape)
dt= t[1]-t[0]; #TIMESTEP (seconds)
visualize_wave(T=R)
visualize_wave(T=-1)
play_waveform(sf=1)(368896,) (368896,)
Sounds data example:
Music-2
in_put = read("jamming-2.wav")
# #DEFINE ARRAYS
R=in_put[0] #SAMPLE RATE
s=in_put[1] #ARRAY
T=len(s)/R
t=np.linspace(0,T,int(R*T)); print(t.shape,s.shape)
dt= t[1]-t[0]; #TIMESTEP (seconds)
visualize_wave(T=R)
visualize_wave(T=-1)
t1=t; s1=s(9491456,) (9491456,)
# CROP-1
t=t1[35*R:50*R]; T=len(t)/R
s=s1[35*R:50*R]; #print(t.shape,s.shape)
visualize_wave(T=4*R)
play_waveform(sf=1.0)# CROP-2
Start=65
t=t1[Start*R:(Start+25)*R]; T=len(t)/R
s=s1[Start*R:(Start+25)*R]; #print(t.shape,s.shape)
visualize_wave(T=0.1*R) # plot 0.1 seconds
visualize_wave(T=4*R) # plot 4 seconds
play_waveform(sf=1.0)[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 198, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 43, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 55, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 198, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 43, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 55, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 198, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 235, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 43, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 55, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 198, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 43, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 55, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 198, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 43, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 55, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 198, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 241, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 43, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 55, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 198, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 43, prop: [atfp], OSStatus: 1852797029
[00007f980f60cad0] auhal audio output error: AudioObjectAddPropertyListener failed, device id 55, prop: [atfp], OSStatus: 1852797029