好久不写技术文章,今天更新一篇。
之前一直在研究google的音频转换(将音频转换为文字),功能。在web上实现之后,想在Windows平台上试试手。就想到了Python,Python有很多UI框架可以用,我用的是PyQT。
Python实现录音的方式很多,简单说下通过PyAudio实现录音的方法;
首先:安装PyAudio,推荐到这里去下载对应版本 http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio
其他地方下载的文件我这里运行都会报错:“Please build and install the PortAudio Python bindings first.”;
先贴上核心代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40from pyaudio import PyAudio,paInt16
from datetime import datetime
import wave
#define of params
NUM_SAMPLES = 2000
framerate = 8000
channels = 1
sampwidth = 2
#record time
TIME = 3
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(framerate)
wf.writeframes("".join(data))
wf.close()
def record_wave():
#open the input of wave
pa = PyAudio()
stream = pa.open(format = paInt16, channels = 1,
rate = framerate, input = True,
frames_per_buffer = NUM_SAMPLES)
save_buffer = []
count = 0
while count < TIME\*4:
#read NUM_SAMPLES sampling data
string_audio_data = stream.read(NUM_SAMPLES)
save_buffer.append(string_audio_data)
count += 1
print ('.')
filename = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")+".wav"
save_wave_file(filename, save_buffer)
save_buffer = []
print ( filename,' saved!')
格式我没做调整,但能保证可以运行。我用的Python版本为3.3,如果报TypeError: sequence item 0: expected string, int found错误,请将wf.writeframes(“”.join(data)) 改为wf.writeframes(b””.join(data),原因是3.3的join函数需要使用unicode格式的参数。