lradc按键录音代码
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import _thread
import time
from evdev import InputDevice
from select import select
import pyaudio
import wave
import os
import sys
dev = InputDevice('/dev/input/event0')
global button_flat
button_flat=False
# 为线程定义一个函数
def scan_key( threadName, delay):
global button_flat
while True:
r,w,x=select([dev],[],[])
for event in dev.read():
print(event)
if event.code==115 and event.value==1:
button_flat=True
# print("按键按下")
if event.code==115 and event.value==0:
button_flat=False
# print("按键松开")
def creat_thread():
# 创建线程
try:
_thread.start_new_thread( scan_key, ("Thread-1", 2, ) )
# _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print ("Error: unable to start thread")
def rec_fun():
global button_flat
#创建按键监控线程
creat_thread()
print("按键初始化完成!")
# 隐藏错误消息,因为会有一堆ALSA和JACK错误消息,但其实能正常录音
os.close(sys.stderr.fileno())
# wav文件是由若干个CHUNK组成的,CHUNK我们就理解成数据包或者数据片段。
CHUNK = 512
FORMAT = pyaudio.paInt16 # pyaudio.paInt16表示我们使用量化位数 16位来进行录音
RATE = 44100 # 采样率 44.1k,每秒采样44100个点。
WAVE_OUTPUT_FILENAME = "/home/pi/chat/command.wav"
print('请按住按钮开始录音...')
while button_flat==False:
continue
# To use PyAudio, first instantiate PyAudio using pyaudio.PyAudio(), which sets up the portaudio system.
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = 1, # cloud speecAPI只支持单声道
rate = RATE,
input = True,
frames_per_buffer = CHUNK)
print("录音中...")
frames = []
# 按住按钮录音,放开时结束
while button_flat == True:
data = stream.read(CHUNK)
frames.append(data)
print("录音完成,输出文件:" + WAVE_OUTPUT_FILENAME + '\n')
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(FORMAT)) # Returns the size (in bytes) for the specified sample format.
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
return
if __name__ == '__main__':
rec_fun()
运行结果:
root@ubuntu:/yangfeiwu/python/key_ctl# python3 key0.py
按键初始化完成!
请按住按钮开始录音...
event at 1583724450.480240, code 115, type 01, val 01
event at 1583724450.480240, code 00, type 00, val 00
录音中...
event at 1583724452.991970, code 115, type 01, val 00
event at 1583724452.991970, code 00, type 00, val 00
录音完成,输出文件:/home/pi/chat/command.wav
录音代码示例
from 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格式的参数。