#!/usr/bin/env python
#version    :       2023.04.04
#language   :       en
from maix import display
from maix import image
from maix import camera
import pyaudio
import wave
import time
import sys
sys.path.append('/root/')
#按键初始化
from CocoPi import BUTTON
key_C = BUTTON(13)

buttonState=0
newState=0
oldState=0
def buttonDetect():
    global buttonState,newState,oldState,key_C
    newState=key_C.is_pressed()
    if newState == True and oldState == False:
        buttonState=1
    elif newState == False and oldState == True:
        buttonState=2
    else:
        buttonState=0
    oldState=newState
    
def timeStampConvert():
    timeListOutput=""
    timeListOutput = str(time.localtime().tm_year) + \
        str(time.localtime().tm_mon)+str(time.localtime().tm_mday) + \
        str(time.localtime().tm_hour)+str(time.localtime().tm_min) + \
        str(time.localtime().tm_sec)
    return timeListOutput

#音频初始化
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100

#屏幕初始化
canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")

image.load_freetype("/root/preset/fonts/CascadiaCodePL-Italic.ttf")
startPointer=0
startTime=0
global deltaTime
deltaTime=0
# 初始化
startTime = time.time()
oldState=0
newState=0
savePathHead="/root/user/audio/"
savePathTail=".wav"
recordState=0
canvas.draw_string(12, 18, "Tip : Press KEY-C to start/stop", 1, color=(0, 255, 0))
canvas.draw_string(58, 48, "recording!", 1, color=(0, 255, 0))
canvas.draw_image(image.open("/root/preset/img/recording.png"),288 , 8,alpha=1)
canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
display.show(canvas)
while True:
    
    buttonDetect()
    if buttonState==2:
        recordState=1-recordState
        print("recordState",recordState)
    if recordState==1:
        if startPointer==0:
            canvas.clear()
            canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
            canvas.draw_string(12, 18, "Tip : Press KEY-C to start/stop", 1, color=(0, 255, 0))
            canvas.draw_string(58, 48, "recording!", 1, color=(0, 255, 0))
            canvas.draw_image(image.open("/root/preset/img/recording.png"),288 , 8,alpha=1)
            canvas.draw_string(24, 108, "Recording start!", 1, color=(0, 255, 0))
            canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
            display.show(canvas)
            print("Recording start!")
            startTime = round(time.time(), 2)
            startPointer=1
            p = pyaudio.PyAudio()
            stream = p.open(format=FORMAT,
                            channels=CHANNELS,
                            rate=RATE,
                            input=True,
                            frames_per_buffer=CHUNK)
            frames = []
        else:
            data = stream.read(CHUNK,exception_on_overflow = False)
            frames.append(data)  
    elif recordState==0:
        if startPointer==1:
            stream.stop_stream()
            stream.close()
            p.terminate()
            WAVE_OUTPUT_FILENAME=savePathHead+timeStampConvert()+savePathTail
            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()
            deltaTime = round(time.time() - startTime, 2)
            canvas.clear()
            canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
            canvas.draw_string(12, 18, "Tip : Press KEY-C to start/stop", 1, color=(0, 255, 0))
            canvas.draw_string(58, 48, "recording!", 1, color=(0, 255, 0))
            canvas.draw_image(image.open("/root/preset/img/recording.png"),288 , 8,alpha=1)
            canvas.draw_string(24, 108, "Recording completed!", 1, color=(0, 255, 0))
            canvas.draw_string(24, 128, "Lasttime:"+str(deltaTime), 1, color=(0, 255, 0))
            canvas.draw_string(24, 148, "File Save Path:", 1, color=(0, 255, 0))
            canvas.draw_string(24, 168, WAVE_OUTPUT_FILENAME, 1, color=(0, 255, 0))
            canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
            
            display.show(canvas)
            print(deltaTime)
            startPointer=0
        else:
            startPointer=0
    else:
        pass