
from machine import Pin
from audio import Record
import audio, _thread, utime

pcm = audio.Audio.PCM(0, 1, 16000, 2, 1)
pcm.setVolume(7)
list = ["_xiao_kai_xiao_kai","_xiao_ki_xiao_ki"]  # 唤醒词
pa = Pin(Pin.GPIO29, Pin.OUT, Pin.PULL_PU, 1)
QuecDuinoPA = Pin(Pin.GPIO39, Pin.OUT, Pin.PULL_PU, 1)
rec = Record(0)

def pcm_thread():
    global pcm, tts
    while True:
        if pcm != None and tts == None:
            pcm_buf = pcm.read(640)
            # if(len(pcm_buf) > 0):
            #     write_len = pcm.write(pcm_buf)
            #     print("1l:", write_len)
            utime.sleep_ms(20)
        elif pcm == None:
            _thread.stop_thread(0)

def tts_paly(str):
    global pcm, tts
    pcm.close()
    pcm = None
    tts=audio.TTS(0)
    tts.setVolume(9)
    tts.play(1, 0, 2, str)
    utime.sleep_ms(100)
    while tts.getState() != 0:
        pass
    tts.close()
    tts = None
    while tts != None:
        pass
    pcm = audio.Audio.PCM(0, 1, 16000, 2, 1)
    _thread.start_new_thread(pcm_thread, ())

tts_paly('我叫小凯')

def kws_cb(para):
    print("kws cb:", para)
    if para[0] == 0:  # 0: 唤醒模式 1: 等待模式
        tts_paly('我在')
        print('我在')

rec.ovkws_set_callback(kws_cb)
rec.ovkws_start(list, 0.5, 1)
