#-*-coding:utf-8-*-
from pyaudio import PyAudio,paInt16
import numpy as np
from datetime import datetime
import wave
import librosa
from math import *
import matplotlib.pyplot as plt
NUM_SAMPLES = 2000
# pyAudio内部缓存的块的大小
SAMPLING_RATE = 8000 #
取样频率
#LEVEL = 1500
SAVE_LENGTH = 8
#COUNT_NUM = 20
channels=1
sampwidth=2
#framerate = 8000
#record time
TIME = 3
#data_path = "voice-data"
#filename1 = '2017-09-01_16_25_50.wav'
#录音
def save_wave_file(filename, data):
'''save the date to the
wav file'''
wf = wave.open(filename,
'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(SAMPLING_RATE)
wf.writeframes("".join(data))
wf.close()
def record_wave():
#open the input of
wave
pa = PyAudio()
stream = pa.open(format
= paInt16, channels = 1,rate = SAMPLING_RATE, input = True,
frames_per_buffer = NUM_SAMPLES)
save_buffer = []
count = 0
while count <
TIME*5:
#read NUM_SAMPLES sampling data
string_audio_data =
stream.read(NUM_SAMPLES)
save_buffer.append(string_audio_data)
count += 1
print count
filename =
"speech1.wav"
save_wave_file(filename,
save_buffer)
save_buffer = []
wav, sr =
librosa.load(filename, mono=True)
#mfcc =
librosa.feature.mfcc(wave, sr)
return wav,sr
if __name__ == '__main__':
filename1 =
'speech.wav'
wav, sr =
librosa.load(filename1, mono=True)
mfcc =
librosa.feature.mfcc(wav, sr)
plt.figure(1)
plt.subplot(211)
plt.plot(wav)
orga = mfcc
#归一化
minVal1 =
np.amin(orga)
maxVal1 =
np.amax(orga)
x1=(orga-minVal1)/(maxVal1-minVal1)
#print "x1",x1
nowb,wr2 =
np.array(record_wave())
mfcc2 =
librosa.feature.mfcc(nowb, wr2)
minVal2 =
np.amin(mfcc2)
maxVal2 =
np.amax(mfcc2)
x2=(mfcc2-minVal2)/(maxVal2-minVal2)
#print "x2",x2
#print len(x2) -
len(x1)
y = []
#每次移动一帧进行对比
for i in
np.arange(0,(len(x2[0]) - len(x1[0]))):
y.append(np.abs(x1[0:,0:] -
x2[0:,i:(len(x1[0])+i)]).sum())
# print "when label =", i,
"mfcc2[0:,i:(len(x1[0])+i)] = ",mfcc2[0:,i:(len(x1[0])+i)]
print y
#print len(y)
#y=np.abs(x1 -
x2).sum()
miny = y[0]
minstate = 0
for j in
np.arange(len(y)):
if y[j] < miny:
miny =
y[j]
minstate =
j
print miny
print minstate
if miny < 15:
print "yes"
plt.subplot(212)
plt.plot(nowb)
plt.show()