python、51微控制器、百度ai介面

QCLZJ發表於2020-10-09
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()









相關文章