L
L
Legor20002020-08-03 16:53:41
Python
Legor2000, 2020-08-03 16:53:41

IndexError: list index out of range I can't figure out how to fix this. How to fix?

import os
import time
import speech_recognition as sr
from fuzzywuzzy import fuzz
import pyttsx3
import datetime

opts = {
  "alias": ('саша', 'сашуня', 'саня', 'александра', 'шурик'),
  "tbr": ('скажи', 'расскажи', 'покажи', 'сколько', 'произвести'),
  "cmds": {
    "ctime": (' текущее время', 'сейчас времени', 'который час'),
    "radio": ('включи музыку', 'воспроизведи радио', 'включи радио'),
    "stupid1": ('ты знаешь анекдот','расскажи анекдот','рассмеши меня'),
  }
}

def speak(what):
  print( what )
  speak_engine.say( what )
  speak_engine.runAndWait()
  speak_engine.stop()

def callback(recognizer, audio):
  try:
    voice = recognizer.recognizer_google(audio, language = "ru-RU")
    print("[log] Распознано: " + voice)

    if voice.startswith(opts["alias"]):

      cmd = voice

      for x in opts['alias']:
        cmd = cmd.replace(x, "").strip()

      for x in opts['tbr']:
        cmd = cmd.replace(x, "").strip()

      cmd = recognize_cmd(cmd)
      execute_cmd(cmd['cmd'])

  except sr.UnknownValueError:
    print("[log] Голос не распознан !")
  except sr.RequestError as e:
    print("[log] Неизвестная ошибка, проверьте интернет !")


def recognize_cmd(cmd):
  RC = {'cmd': '', 'percent': 0}
  for c, v in opts['cmd'].items():

    for x in v :
      vrt = fuzz.ratio(cmd, x)
      if vrt > RC['percent']:
        RC['cmd'] = c
        RC['percent'] = vrt
        
  return RC

def execute_cmd(cmd):
  if cmd == 'ctime':
    now = datetime.datetime.now()
    speak("Сейчас " + str(now.hour) + " : " + str(now.minute))
  elif cmd == 'radio':
    os.system("C:/Python/music.mp3")

  elif cmd == 'stupid1':
    speak("Мой разработчик не научил меня анекдотам !")
  
  else :
    print("Команда не распознана !")


r = sr.Recognizer()

m = sr.Microphone(device_index = 1)

with m as source:
  r.adjust_for_ambient_noise(source)

speak_engine = pyttsx3.init()


voices = speak_engine.getProperty('voices')

speak_engine.setProperty('voice', voices[4].id)

speak("Добрый день, пользователь")
speak("Саша слушает")

stop_listening = r.listen_in_background(m, callback)
while True: time.sleep(0.1)


And it outputs this:
Traceback (most recent call last):
  File "First2.py", line 92, in <module>
    speak_engine.setProperty('voice', voices[4].id)
IndexError: list index out of range

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
milssky, 2020-08-03
@Legor2000

1. Will you learn how to wrap your code in the appropriate tag or not?
2. Obviously, there are fewer votes than 5, hence the error.

P
PavelMos, 2020-08-03
@PavelMos

The compiler indicates that the problem is in
voices, in which the data from speak_engine.getProperty('voices')
You can directly see what is in it, for example:
voices = speak_engine.getProperty('voices')
print (voices)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question