Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. import os
  2.  
  3. import speech_recognition as sr
  4.  
  5. from pydub import AudioSegment
  6. from pydub.playback import play
  7. from gtts import gTTS as tts
  8.  
  9.  
  10. def speak(text):
  11. """Say something"""
  12.  
  13. # Write assistant's output to console
  14. print(text)
  15.  
  16. # Save audio file
  17. speech = tts(text=text, lang='en')
  18. speech_file = 'input.mp3'
  19. speech.save(speech_file)
  20.  
  21. # Play audio file
  22. sound = AudioSegment.from_mp3(speech_file)
  23. play(sound)
  24. os.remove(speech_file)
  25.  
  26.  
  27. def capture():
  28. """Capture audio"""
  29.  
  30. rec = sr.Recognizer()
  31.  
  32. with sr.Microphone() as source:
  33. print('I\'M LISTENING...')
  34. audio = rec.listen(source, phrase_time_limit=5)
  35.  
  36. try:
  37. text = rec.recognize_google(audio, language='en-US')
  38. return text
  39.  
  40. except:
  41. speak('Sorry, I could not understand what you said.')
  42. return 0
  43.  
  44.  
  45. def process_text(name, input):
  46. """Process what is said"""
  47.  
  48. speak(name + ', you said: "' + input + '".')
  49. return
  50.  
  51.  
  52. if __name__ == "__main__":
  53.  
  54. # First get name
  55. speak('What is your name?')
  56. name = capture()
  57. speak('Hello, ' + name + '.')
  58.  
  59. # Then just keep listening & responding
  60. while 1:
  61. speak('What do you have to say?')
  62. captured_text = capture().lower()
  63.  
  64. if captured_text == 0:
  65. continue
  66.  
  67. if 'quit' in str(captured_text):
  68. speak('OK, bye, ' + name + '.')
  69. break
  70.  
  71. # Process captured text
  72. process_text(name, captured_text)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement