import wave
import pyaudio
from aip import AipSpeech
import serial
import 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())
b = int(b, 16)
b = hex(b)[2:]
c = binascii.unhexlify(b)
com.write(c)
send_data()