python、51单片机、百度ai接口

import wave
import pyaudio
from aip import AipSpeech
import serial  # 导入pyserial模块,串口通信相关
import binascii  # 导入binascii模块,进制与进制转换、进制与字符串转换相关


""" 你的 APPID AK SK """
APP_ID = '#####'
API_KEY = '######'
SECRET_KEY = '##########'

# 读取文件
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


# 录音功能
def record_content():
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 16000
    RECORD_SECONDS = 3

    WAVE_OUTPUT_FILENAME = "audio.wav"
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=CHANNELS,
                    rate=RATE, input=True,
                    frames_per_buffer=CHUNK)
    print("* recording")

    frames = []
    for j in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)

    print("* done recording")

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()
    print("done ------------------------------   ")
    return WAVE_OUTPUT_FILENAME


# 生成语音功能客户端
client_audio = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

# 语音录制
filePath = record_content()

# 语音识别
result_audio = client_audio.asr(get_file_content(filePath), 'wav', 16000, {
     
    'dev_pid': 1537,
})
content_audio = result_audio['result'][0]
print(content_audio)



#串口通讯
com = serial.Serial('COM9', 4800)  # 打开串口,设置波特率

def send_data():  # 发送数据函数
    while True:
        if (content_audio == '开启风扇。'):
            x='A'
        elif (content_audio == '关闭风扇。'):
            x='B'

        b = binascii.b2a_hex(x.encode())  # 二进制形式转换成16进制比特流形式
        b = int(b, 16)  # 16进制比特流变成整型数据
        b = hex(b)[2:]  # 16进制的整型数
        c = binascii.unhexlify(b)  # 16进制解码成字节流
        com.write(c)

send_data()









你可能感兴趣的:(小实战,自然语言处理,python,单片机,串口通信)