首页 > 解决方案 > 虚拟助手python

问题描述

大家好,我正在尝试开发一个虚拟助手,它将帮助我完成一些项目,所以我试图获得最终项目的基础知识,但是我收到一个错误(UnboundLocalError: local variable 'command' referenced before assignment),我试图更改return command为 underprintf(command)但它不让我说话,并且终端上出现一条消息 NONE 和另一个错误(TypeError: argument of type 'NoneType' is not iterable)。那么我怎样才能不停地完成这项工作呢?

下面的代码:

import pyttsx3
import pywhatkit
import datetime

listener = sr.Recognizer()
engine = pyttsx3.init()

def talk(text):
    engine.say(text)
    engine.runAndWait()

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'skor' in command:
                command = command.replace ('skor', '')
                print(command)
    except:
        pass
    return command
def run_skor():
    command = take_command()
    print(command)
    if 'play on youtube' in command:
        song = command.replace ('play on youtube', '')
        talk('playing' + song)
        pywhatkit.playonyt(song)
    elif 'search on google' in command:
        sea = command.replace ('search on google', '')
        talk ('searching' + sea)
        pywhatkit.search(sea)
    elif 'tell me the time' in command:
        time = datetime.datetime.now().strftime('%H:%M')
        print(time)
        talk('Current time is' + time)
while True:
    run_skor()```

标签: pythonpython-3.9

解决方案


def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = r.listen(source)

        try:
        print("Recognizing...")
        command = r.recognize_google(audio, language='en-in')
        print(f"User said: {command}\n")

    except Exception as e:
        print("Say that again please...")
        return "None"

    return command.lower()

推荐阅读