1# -*- coding: utf-8 -*- 2import os 3import sys 4import math 5import wave 6import struct 7import numpy as np 8 9max_volume = 0.85 10max_short = 32767 11min_short = -32768 12sample_rate = 16000 13min_freq = 1700 14max_freq = 1700 + 96 * 50 + 100 15freq_inc = 50 16time_inc = 0.1 17 18def gen_voice_freq(freq, times): 19 unit_sample = int(sample_rate*times) 20 theta_inc = 2 * math.pi * freq / sample_rate 21 df = sample_rate / (unit_sample - 1) 22 theta = 0 23 buffer = [] 24 for frame in range(unit_sample): 25 tmp = math.pow(frame - unit_sample/2, 2) / math.pow(unit_sample/2, 2) 26 vol = max_volume * math.sqrt(1 - tmp) 27 fv_float = vol * math.cos(theta) 28 fv_float_16 = int(max_short * fv_float) 29 if fv_float_16 > max_short: 30 fv_float_16 = max_short 31 if fv_float_16 < min_short: 32 fv_float_16 = min_short 33 buffer.append(fv_float_16) 34 theta += theta_inc 35 if theta > 2.0 * math.pi: 36 theta -= 2.0 * math.pi 37 print('freq: %d' %freq) 38 Y = np.fft.fft(buffer)*2/unit_sample 39 absY = [np.abs(x) for x in Y] 40 #print(absY) 41 print(int(np.argmax(absY)*df)) 42 return buffer 43 44''' 45 i = 0 46 while i < len(absY): 47 if absY[i] > 0.01: 48 print("freq: %d, Y: %5.2f + %5.2f j, A:%3.2f, phi: %6.1f" % (i, Y[i].real, Y[i].imag, absY[i], math.atan2(Y[i].imag, Y[i].real)*180/math.pi)) 49 i+=1 50''' 51 52 53def gen_voice(text, wav_file): 54 wave_data = [] 55 wave_data += gen_voice_freq(min_freq - 50, 0.128) 56 for c in text: 57 if c == '\n' : 58 freq = max_freq 59 print('max freq : %d' % freq) 60 else : 61 freq = min_freq + (ord(c) - 33)*freq_inc 62 wave_data += gen_voice_freq(freq, 0.128) 63 freq = min_freq + (ord('f') - 33)*freq_inc 64 wave_data += gen_voice_freq(freq, 0.128) 65 freq = min_freq + (ord('c') - 33)*freq_inc 66 wave_data += gen_voice_freq(freq, 0.128) 67 wave_data += gen_voice_freq(min_freq - 50, 0.128) 68 69 f = wave.open(wav_file,"wb") 70 f.setnchannels(1) 71 f.setsampwidth(2) 72 f.setframerate(sample_rate) 73 for data in wave_data: 74 f.writeframes(struct.pack('h', int(data))) 75 f.close() 76 77def main(args): 78 gen_voice("h3c_router01\n123456", "test.wav") 79 #gen_voice_freq(5650, 0.1) 80 81if __name__ == '__main__': 82 main(sys.argv[1:]) 83