Python Forum
pyttsx3 cutting off last word
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pyttsx3 cutting off last word
#1
Hello,

I got my python script to work using Text-To-Speech output but when I run it, it cuts off the last word or letters.
Ex:
speak("How may I be of service?")  
Will say "How may I be of Serv-" and the "-ice" get's cut off.

Is there a way to fix this? I tried playing around with the speech rate but it didn't help.

Any help is appreciated,
Thanks.

Here's The full code:
#!/usr/bin/env python3

import json
import random
import datetime
import operator
import os
import time
import sys
import requests
from bs4 import BeautifulSoup
from Weather import *
import wikipedia
import wolframalpha
import pyttsx3
import speech_recognition as sr 
from Animations import startupAnimation

#-------------------------------------------------------------------------------------
                            #Commander Name (You) and A.I Name
#-------------------------------------------------------------------------------------
Commander = "Commander"
AI_Name = 'Baxter'
#-------------------------------------------------------------------------------------

def speak(audio):
    engine = pyttsx3.init()
    voices = engine.getProperty('voices')
    engine.setProperty('voice',voices[1].id)
    engine.setProperty('rate', 125)
    engine.setProperty('volume', 1.0)
    engine.say(audio)
    engine.runAndWait()
    

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning" + Commander)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)   
    else:
        speak("Good Evening" + Commander) 


def listenCommand():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)  
    #---------------------------
    # Uses google API to listen
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')
    #--------------------------------

    except:
            pass

    return command 

wishMe()
speak("How may I be of service?")  

#Initiate Start Up Animation
#startupAnimation()

while True:
    command = listenCommand()
    command=str(command).lower()

    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
    if ('weather' not in command): 
        if ('who is' in command) or ('what is the' in command) or ('what is a' in command) or ("what is" in command):
            if ('time' not in command):
                if ('news' not in command):
                    speak('Searching Wikipedia...')
                    command = command.replace("who is","")
                    command = command.replace("what is the","")
                    command = command.replace("what is a","")
                    command = command.replace("what is","")
                    results = wikipedia.summary(command, sentences = 2)
                    #----------------------
                    #Auto typing animation:
                    print("Baxter: ", end="")
                    for i in results:
                        sys.stdout.write(i)
                        sys.stdout.flush()
                        time.sleep(0.05)
                    print("\n")
                    #----------------------
                    speak(results) 
    #-------------------------------------------------------------------------------------
                    #Search Wolfram Alpha (Math/Conversions, Definitions)
    #-------------------------------------------------------------------------------------
    if ('weather' not in command):
        if ('news' not in command):
            if ('calculate' in command) or ("what's" in command) or ('define' in command):
                speak('Searching Wolfram Alpha...')
                command = command.replace("calculate","")
                command = command.replace("what's","")
                command = command.replace("define","")
                # Wolframalpha App Id
                appId = 'JH9XHR-W9J76L7H5A'
                # Wolfram Instance
                client = wolframalpha.Client(appId)
                res = client.query(''.join(command))
                results = next(res.results).text
                #----------------------
                #Auto typing animation:
                print("Baxter: ", end="")
                for i in results:
                    sys.stdout.write(i)
                    sys.stdout.flush()
                    time.sleep(0.05)
                print("\n")
                #----------------------
                speak(results) 
    #-------------------------------------------------------------------------------------
                                    #Search News
    #-------------------------------------------------------------------------------------
    if ('news' in command):
        speak('Searching news networks...')
        command = command.replace("news","")
        #Gets the news headlines from this url:
        url='https://www.google.com/search?q=windsor+news&client=firefox-b-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjFr5SwoJb1AhXELs0KHdabBAEQ_AUoAXoECAEQAw&biw=1024&bih=486'
        results = requests.get(url)
        soup = BeautifulSoup(results.text, 'html.parser')
        headlines = soup.find('body').find_all('h3')
        for x in headlines:
            print("Baxter:",x.text.strip())
        speak(results) 
    #-------------------------------------------------------------------------------------
                                        #Search Weather
    #-------------------------------------------------------------------------------------
    if ('weather' in command):
        if ('week' in command):
            speak('Searching weather networks...')
            command = command.replace("weather for the week","")
            #Call weather data for the week:
            displayWeeksWeatherData()
        else:
            speak('Searching weather networks...')
            command = command.replace("weather","")
        #Call weather data for today:
        displayWeatherData()
    #-------------------------------------------------------------------------------------
                                        #Tell Time
    #-------------------------------------------------------------------------------------
    elif ('time' in command):
        speak('Scanning local clock networks...')
        command = command.replace("time","")
        strTime = datetime.datetime.now().strftime("%I:%M%P")
        speak("The time is {strTime}")
        print("Baxter: The time is ", strTime)
    #-------------------------------------------------------------------------------------
                                #Enter the Matrix (Easter Egg)
    #-------------------------------------------------------------------------------------
    elif ('matrix' in command):
        speak('Entering the matrix...')
        command = command.replace("matrix","")
        response = "Taking the red pill..."
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in response:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.2)
        print("\n")
        #----------------------
        time.sleep(2)
        os.system("cmatrix")
    #-------------------------------------------------------------------------------------

    #-------------------------------------------------------------------------------------
                                #Stop Program/Script Command
    #-------------------------------------------------------------------------------------
    elif ('stop' in command) or ('shutdown' in command) or ('quit' in command):
        speak("Shutting Down...")
        response = "Terminating program..."
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in response:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.2)
        print("\n")
        #----------------------
        exit()
    #-------------------------------------------------------------------------------------
Reply
#2
This works perfectly on my system. Try it and let me know if it works.
import pyttsx3

speaker = pyttsx3.init ()
speaker.setProperty ('rate', 120)
speaker.say ('How may I be of service?')
speaker.runAndWait ()
EDIT : Your code runs perfectly on my system as well.
import pyttsx3
 
def speak(audio):
    engine = pyttsx3.init()
    # voices = engine.getProperty('voices')
    # engine.setProperty('voice',voices[1].id)
    engine.setProperty('rate', 125)
    engine.setProperty('volume', 1.0)
    engine.say(audio)
    engine.runAndWait()
     
speak ('How may I be of service?') 
Reply
#3
Quote:speaker = pyttsx3.init ()
speaker.setProperty ('rate', 120)
speaker.say ('How may I be of service?')
speaker.runAndWait ()
Thanks, that worked!
For some strange reason engine.say() will cut it off but speaker.say() won't.

EDIT: After some quick testing It turns out that engine.setProperty('voice',voices[1].id) the voices[1].id was the issue. I changed it to voices[2].id (a female voice) and it didn't cut anything off. Still strange that voices[1].id is the only voice that cuts off the last word.

I have one other question though. Is it possible to have my speech output run as the text is being displayed on the screen (through the auto-type/typewriter animation). Right now the text will "typewrite" to the screen, then the speech output will start. Is there anyway the can work simultaneously?
Reply
#4
(Feb-28-2022, 10:33 PM)Extra Wrote: I have one other question though. Is it possible to have my speech output run as the text is being displayed on the screen (through the auto-type/typewriter animation). Right now the text will "typewrite" to the screen, then the speech output will start. Is there anyway the can work simultaneously?
This would be my best shot at that.
import sys
import time
import pyttsx3
import threading

engine = pyttsx3.init ()
engine.setProperty ('rate', 120)

def tell (*output_array) :
	output_string = ' '.join (output_array)
	engine.say (output_string)
	engine.runAndWait ()

def show_and_tell (output_string) :
		output_array = output_string.split ()
		telling = threading.Thread (target = tell, args = (output_array))
		telling.start ()
		for letter in output_string :
			print (letter, end = '')
			sys.stdout.flush ()
			time.sleep (0.08)
		print ()

show_and_tell ('How may I be of service?')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Controlling text-to-speech pauses with pyttsx3 pmac1300 4 4,483 Mar-14-2022, 06:47 AM
Last Post: Coricoco_fr
  pyttsx3 problem Tyrel 0 1,118 Feb-05-2022, 08:53 AM
Last Post: Tyrel
  Know when the pyttsx3 engine stops talking UsualCoder 3 3,239 Aug-29-2021, 11:08 PM
Last Post: snippsat
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,518 Aug-12-2021, 04:25 PM
Last Post: palladium
  Input function cutting off commands at spaces. throwaway34 3 2,214 May-12-2021, 06:40 AM
Last Post: throwaway34
  working with pyttsx3 gr3yali3n 0 1,613 Nov-24-2020, 09:40 AM
Last Post: gr3yali3n
  Python Speech recognition, word by word AceScottie 6 16,032 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage
  Python PIL cutting off text. DreamingInsanity 3 2,577 Oct-25-2019, 09:00 AM
Last Post: DreamingInsanity
  print a word after specific word search evilcode1 8 4,868 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  pyttsx3 cuts off when run from py file duelistjp 4 4,086 Dec-20-2018, 04:54 PM
Last Post: DrNerdly118

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020