ИИ не распознаёт мой микрофон. SpeechRecognition

Рейтинг: 1Ответов: 1Опубликовано: 05.02.2023

Я делал ИИ, и у меня возникла проблема, что ии по какой-то причине не распознаёт мой микрофон. Подскажите пожалуйста, в чём проблема? Мой микрофон в полном порядке и он работает.

Код:

import sys
import time
import webbrowser

import pyttsx3
import speech_recognition as sr
import pyautogui as pg


tts = pyttsx3.init()
def talk(words):
    tts.say(words)
    print(words)
    tts.runAndWait()

talk("Спроси")

def command():
    r = sr.Recognizer()

    with sr.Microphone() as source:
        print("Говорите...")
        r.pause_threshold = 1
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)

    try:
        zadanie = r.recognize_google(audio, language="ru-RU").lower()
        print("Вы сказали:", zadanie)
    except sr.UnknownValueError:
        talk("Я вас не поняла")
        zadanie = command()

    return zadanie

def makeSomething(zadanie):
    if 'открой яндекс' in zadanie:
        talk("Уже открываю")
        url = 'https://ya.ru/'
        webbrowser.open(url)
    elif 'стоп' in zadanie:
        talk("Да конечно")
        sys.exit()
    elif 'привет' in zadanie:
        talk('привет')
    elif 'напиши код' in zadanie:
        talk('Окей, без проблем')
        pg.leftClick(99, 157, duration=0.5)
        pg.click(136, 161, duration=1)



while True:
    makeSomething(command())

Ошибка: введите сюда описание изображения

Ответы

▲ 1Принят

К ИИ ведь тоже подход нужен, не правильно с ним обращаешься, вот он и не хочет с тобой дружить ;-)

import webbrowser

import pyttsx3
from speech_recognition import Microphone, Recognizer, UnknownValueError, RequestError


class VoiceAssistant:
    def __init__(self):
        self.__recognizer = Recognizer()
        self.__tts = pyttsx3.init()

    def waiting_command(self):
        try:
            with Microphone() as source:
                print("Говорите...")
                self.speak("Ожидаю команды...")
                self.__recognizer.pause_threshold = 1
                self.__recognizer.adjust_for_ambient_noise(source, duration=1)
                audio = self.__recognizer.listen(source)
        except OSError:
            self.speak("Проверьте микрофон...")
            return
        try:
            command = self.__recognizer.recognize_google(audio, language="ru-RU").lower()
            print("Вы сказали:", command)
            return command
        except UnknownValueError as e:
            self.speak(f"Упс... ошибочка - {e}")
            return "Не поняла, повторите!"
        except RequestError as e:
            self.speak(f"Упс... ошибочка - {e}")

    def perform_command(self, command: str):
        match command:
            case 'открой браузер':
                webbrowser.open("https://yandex.ru")
            case 'всё спасибо ты свободна':
                self.speak("до свидания")
                exit(0)

    def speak(self, text: str):
        self.__tts.say(text)
        self.__tts.runAndWait()


def main():
    voice_assistant = VoiceAssistant()
    while True:
        command = voice_assistant.waiting_command()
        voice_assistant.perform_command(command)


if __name__ == '__main__':
    main()