首页 > 解决方案 > 如何在python中的元素中使用语音识别进行输入

问题描述

import speech_recognition as sr 
import pyttsx3
import string
import random
#Text To Speech
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
#print(voices)
engine.setProperty('voice',voices[0].id)
engine.setProperty('rate', 145) #you can replace it to incease or decrease dound speed default(200)
def speak(audio):  #here audio is var which contain text
    engine.say(audio)
    engine.runAndWait()
#now convert audio to text
def takecom():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listning....")
        audio = r.listen(source)
    try:
        print("Recognising....") 
        text = r.recognize_google(audio,language='en-in')
        print(text)
    except Exception:      
        speak("error...")
        print("Network connection error") 
        return "none"
    return text
#for main function                               
if __name__ == "__main__":
    while True:
        query = takecom().lower()
        if 'create password' in query or 'c' in query :
            if __name__ == "__main__":
                s1 = string.ascii_lowercase
                s2 = string.ascii_uppercase
                s3 = string.digits
                s4 = string.punctuation
                speak('what do you want to keep the length of the password type here')
                plen =int(input('what is the length of the password'))  #p
                s=[]
                s.extend(list(s1))
                s.extend(list(s2))
                s.extend(list(s3))
                s.extend(list(s4))
                print("Your password is:")
                print("".join(random.sample(s,plen)))
                speak("".join(random.sample(s,plen)))
        elif query == 'none':
            continue 
        elif 'exit' in query or 'abort' in query or 'stop' in query or 'bye' in query or 'quit' in query:
            ex_exit = 'ok byy'
            speak(ex_exit)
            exit()   

当我运行此代码时,一切正常,但它要求写入密码的长度,当我在其中写入长度时,代码继续,但我不想在其中写任何东西有什么办法可以让我在函数 plen (#p) 中提供语音输入,以在语音命令的帮助下完成程序工作。我正在使用 python 3.8

标签: pythonstringspeech-recognitionspeech-to-text

解决方案


改一下↓</p>

plen =int(input('what is the length of the password'))  #p

↓</p>

plen =int(takecom())  #p

推荐阅读