基于音调识别男人女人的算法研究---python实现

Test,see if codes are rightly displayed

 

 1 from __future__ import division
 2 from matplotlib import pylab as plt
 3 import numpy as np
 4 import scipy.io.wavfile
 5 from scipy.signal import kaiser, decimate
 6 from copy import copy
 7 import os, re
 8 
 9 correct_count = 0
10 
11 def analyze(filename):
12   global correct_count
13 
14   print(analyzing  + filename +  ...)
15   try:
16     sampling_rate, signal = scipy.io.wavfile.read(filename)
17   except:
18     print("unable to analyze " + filename)
19     print("")
20   else:
21     samples_count = len(signal)
22     duration = float(samples_count) / sampling_rate
23     if not isinstance(signal[0], np.int16):
24       signal = [s[0] for s in signal]
25     signal = signal * kaiser(samples_count, 100)
26 
27     spectrum = np.log(abs(np.fft.rfft(signal)))
28     hps = copy(spectrum)
29     for h in np.arange(2, 6):
30       dec = decimate(spectrum, h)
31       hps[:len(dec)] += dec
32     peak_start = 50 * duration
33     peak = np.argmax(hps[peak_start:])
34     fundamental = (peak_start + peak) / duration
35 
36     if fundamental < 165:
37       verdict = M
38     elif 180 < fundamental:
39       verdict = F
40     else:
41       verdict = U
42 
43     correct = re.search(([KM])\.wav, filename).group(1)
44     if correct == K:
45       correct = F
46 
47     if correct == verdict:
48       correct_count += 1
49 
50     print("fundamendal frequency: " + "%.5f" % fundamental)
51     print("verdict: " + verdict)
52     if correct != verdict:
53       print("WRONG")
54     print("")
55 
56     #print(sampling_rate, duration, len(frequency[::duration]))
57 
58     #plt.plot(hps)
59     #plt.show()
60 
61 filenames = os.listdir(wav)
62 for filename in filenames:
63   analyze(wav/ + filename)
64 
65 accuracy = float(correct_count) / len(filenames)
66 print("accuracy: %.2f%%" % (accuracy * 100))
67 
68 #analyze(‘wav/002_M.wav‘)

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。