Audio does not complete when called from another function - python

I have the following code quasi-working
from gtts import gTTS
import speech_recognition as rs
import pyaudio
import audioop
import os
import math
from os import system
import threading
from datetime import datetime
def say(text):
filename = 'speak.mp3'
language = 'en'
myobj = gTTS(text=text, lang=language, slow=False)
myobj.save(filename)
player = vlc.MediaPlayer(filename)
player.play()
def listen(x):
r=rs.Recognizer()
with rs.Microphone() as source:
audio=r.listen(source)
try:
text = r.recognize_google(audio)
process(text.lower())
except:
system('say I did not get that. Please say again.')
listen(0)
def process(text):
print(text)
# Do things here based on text
if 'what time is it' in text:
say(datetime.now().strftime("%H%M"))
return
#process("what time is it") "Seventeen oh six"
# Listen for me to say something, if I say 'what time is it' return the time
#listen(0) "Se"
If I run process(text) manually such as:
process("what time is it")
Python will speak back to me something like "1706" (Seventeen oh six)
However, if I call it from the listen() function python will start to play the file but it gets cut off and is more like "Se" and then nothing.
I've tried multiple things including using time.sleep(n) but no changes seem to make the entire file play when called through the listen(n) function.

Related

How to add emojis in the code for automating with PYAUTOGUI

import time
from datetime import datetime
import pyautogui
import os
import emoji
text = emoji.emojize(":thumbs_up:")
Time = input("Enter your time here:")
while(True):
present = datetime.now()
present = present.strftime("%H:%M")
if (present == Time):
pyautogui.write(text , interval=0.25)
time.sleep(2)
pyautogui.press("enter")
time.sleep(2)
break
Can anyone help me how to make pyautogui type emojis too?
im a beginner....
you can use
pyautogui.hotkey("alt", "ALT CODE HERE")
and place alt code of emoji in the "ALT CODE HERE" section

While Loop No Longer Updating Data when added "Press Enter to Exit"

I am a beginner to Python and recently was making a **Discord Rich Prescense** application. The problem is that I was using a While Loop and added a "*Press Enter to Exit*" feature. This made the Rich Prescense stuck on One Quote. I have attached a screenshot of the problem.
from config import credentials
from data import quotes
from pypresence import Presence
import random
import time
def quotegen():
RPC = Presence(credentials.clientid)
RPC.connect()
while True:
RPC.update(details="Random Quote:", state=random.choice(quotes.quotes))
i = input("Press Enter to Exit")
time.sleep(30)
if not i:
break
Screenshot of what its supposed to do:
Using the keyboard module (https://pypi.org/project/keyboard/)
you can do it all.
I modified your code to fit your requirements:
import keyboard # using module keyboard
from config import credentials
from data import quotes
from pypresence import Presence
import random
import time
def quotegen():
RPC = Presence(credentials.clientid)
RPC.connect()
while True:
RPC.update(details="Random Quote:", state=random.choice(quotes.quotes))
i = input("Press Enter to Exit")
time.sleep(30)
if keyboard.is_pressed('enter'): # if key 'enter' is pressed
break

Python Speech Recognition not starting without saying anything

I am creating a Python Personal Assistant using Python's Speech Recognition,pyaudio and Python Text to speech modules, so what I want is that after starting the program I want it to say something and have coded it the same, but when I run the program, It starts listening first and until and unless I provide it with any random word it does not move forward. Here is the code for the main function.
import speech_recognition as sr
import random
import functions.Response as speech
import functions.custom_input
import functions.device_stats
import num2words
import sys,os
import functions.check_user
from functions.Response import say,listen
def check():
say("Starting Program")
say("Initializing modules")
say("Modules Intialized")
say("Performing System Checks")
say("Sytem Checks Done")
say("Starting happy protocol")
check()
Any Idea? what to do?
Your program is missing a lot of information. This is not a problem because I have been where you are. You are missing some lines of code. Instead of importing things like the say function or response, here is a working and simpler alternative.
import pyttsx3
import speech_recognition as sr
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def say(audio):
engine.say(audio)
engine.runAndWait()
def check():
say("Starting Program")
say("Initializing modules")
say("Modules Intialized")
say("Performing System Checks")
say("Sytem Checks Done")
say("Starting happy protocol")
check()
And you can essentially add commands for your virtual assistant later on...

how to play songs one by one in the folder?using WMPlayer.OCX

i got this code in by googling it and i have tried this code but it plays only songs which we are giving .
i need code to play all the songs in the folder,one by one until i stops.
import time
from win32com.client import Dispatch
songs_dir='G:\songs\My Fav'
songs = os.listdir(songs_dir)
mp = Dispatch("WMPlayer.OCX")
tune = mp.newMedia("{}\\{}".format(songs_dir,songs[2]))
mp.currentPlaylist.appendItem(tune)
mp.controls.play()
time.sleep(1)
mp.controls.playItem(tune)
print("Playing music")
a=input("Press Enter to stop playing")
mp.controls.stop()```
Remove input because it pauses your script
Use time.duration to wait for the song complete
Code:
import time
import glob
from win32com.client import Dispatch
for file in glob.glob(r'C:\Users\MUSIC\*'):
print(f'Playing: {file}')
mp = Dispatch('WMPlayer.OCX')
tune = mp.newMedia(file)
mp.currentPlaylist.appendItem(tune)
mp.controls.play()
time.sleep(1)
mp.controls.playItem(tune)
time.sleep(int(tune.duration))

How to make my Text-To-Speech program fully portable and usable on every Operating System?

I have a Text-To-Speech program that asks for a user input and then outputs that input as speech. It will then ask if the user wants to convert another input into speech or whether they want to exit the program. At the moment the program will only work on Windows as it is dependent on Windows Media Player to play the text-to-speech file. How could I make it so it plays the file from within Python, and, by extension, works on every operating system? If there are any other parts within the code that would prevent it from running on other Operating Systems, please tell me what they are and how I could change them as well. Thanks!
try:
import os
import time
import sys
import getpass
import pip
import subprocess
from contextlib import contextmanager
my_file = "Text To Speech.mp3"
wmp = "C:\Program Files (x86)\Windows Media Player\wmplayer.exe"
media_file = os.path.abspath(os.path.realpath(my_file))
username = getpass.getuser()
#contextmanager
def suppress_output():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
def check_and_remove_file():
if os.path.isfile(my_file):
os.remove(my_file)
def input_for_tts(message):
tts = gTTS(text = input(message))
tts.save('Text To Speech.mp3')
subprocess.Popen([wmp, media_file])
audio = MP3(my_file)
audio_length = audio.info.length
time.sleep((audio_length) + 2) # Waits for the audio to finish playing before killing it off.
os.system('TASKKILL /F /IM wmplayer.exe')
time.sleep(0.5) # Waits for Windows Media Player to fully close before carrying on.
with suppress_output():
pkgs = ['mutagen', 'gTTS']
for package in pkgs:
if package not in pip.get_installed_distributions():
pip.main(['install', package])
from gtts import gTTS
from mutagen.mp3 import MP3
check_and_remove_file()
input_for_tts("Hello there " + username + """. This program is
used to output the user's input as speech.
Please input something for the program to say: """)
while True:
answer = input("""
Do you want to repeat? (Y/N) """).strip().lower()
if answer in ["yes", "y"]:
input_for_tts("""
Please input something for the program to say: """)
elif answer in ["no", "n"]:
check_and_remove_file()
sys.exit()
else:
print("""
Sorry, I didn't understand that. Please try again with either Y or N.""")
except KeyboardInterrupt:
check_and_remove_file()
print("""
Goodbye!""")
sys.exit()
Instead of using Windows Media Player you can use an audio playing package. An good package that can do this is PyMedia.

Categories