python写按键(lradc)录音程序

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格式的参数。

参考:https://blog.it2048.cn/article-pythonluyin/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yfw&武

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值