Python WinSound: Runtime Error after writing to wav - python

I'm trying to make a program that plays text-to-speech with gTTS.
import gtts
import winsound
import time
def playtts(strin):
fl = gtts.gTTS(text = strin, lang = 'en')
fl.save('temp.wav')
time.sleep(3)
winsound.PlaySound('temp.wav', winsound.SND_FILENAME | winsound.SND_NOSTOP | winsound.SND_NODEFAULT)
playtts("HELLO THERE")
When I run it, I get:
File "[DATA EXPUNGED]", line 14, in <module>
playtts("HELLO THERE")
File "[DATA EXPUNGED]", line 12, in playtts
winsound.PlaySound('temp.wav', winsound.SND_FILENAME | winsound.SND_NOSTOP | winsound.SND_NODEFAULT)
RuntimeError: Failed to play sound
>>>
When I open the file in Media Player, it works just fine. Why is it raising errors?

import gtts
import winsound
import time,os
def playtts(strin):
fl = gtts.gTTS(text = strin, lang = 'en')
fl.save('temp.wav')
time.sleep(3)
os.system("start temp.wav")
playtts("whiskers whats up")
Here's a way to do it without winsound it opens a media player and then plays it for you and you.

Related

How do I run a python file inside another python file?

I'm working on a mac. I get a Permission denied exception when running code. How do I run one python file inside the main python file?
import os
import telebot
from telebot import types
# --------------------------\ project files /-------------------------#
from auth_data import token, txt
bot = telebot.TeleBot(token)
# first launch, start of work
#bot.message_handler(commands=['start', 'help'])
def welcome(message):
markup = types.InlineKeyboardMarkup(row_width=1)
parse = types.InlineKeyboardButton('📩Get messages📩', callback_data='parse')
markup.add(parse)
photo = open('menu.jpg', 'rb')
bot.send_photo(message.chat.id, photo, caption=txt, reply_markup=markup, parse_mode="HTML")
# menu
#bot.callback_query_handler(func=lambda call: True)
def callback(call):
if call.message:
if call.data == 'parse':
os.system('/Users/valiev/code/python/telegram_bot_parser/parser.py')
if __name__ == '__main__':
bot.infinity_polling(none_stop=True, interval=0)
You are not running the file, but opening it. Try changing
os.system('/Users/valiev/code/python/telegram_bot_parser/parser.py')
to
os.system('python3 /Users/valiev/code/python/telegram_bot_parser/parser.py')

I'm trying to make an alarm clock (from a tutorial) in Python, Playsound isn't activiting sound

I'm trying to make an alarm clock, and it works for the most part. But I installed playsound so I could make it play music when it goes off as an alarm clock should. I'm not quite sure how to use paths and even when I place the .wav in the folder it's meant to be it doesn't play.
Code:
import datetime
from playsound import playsound
alarmHour = int(input("What hour do you want to wake up?"))
alarmMinute = int(input("What minute do you want?"))
amPm = str(input("Am or Pm")).lower().strip()
if (amPm == "pm"):
alarmHour = alarmHour + 12
while(1 == 1):
if(alarmHour == datetime.datetime.now().hour and
alarmMinute == datetime.datetime.now().minute):
print("Wake up, lazy!")
playsound("C:\\Users\\wicke\\AppData\\Local\\Programs\\Python\\Python39\\Lib\\site-packages\\askaway.wav")
break
print("Exited")
The error:
Error 275 for command:
open "C:\Users\jeandae\AppData\Local\Programs\Python\Python39\Lib\site-packages\askaway.wav"
Cannot find the specified file. Make sure the path and filename are correct.
Error 263 for command:
close "C:\Users\jeandae\AppData\Local\Programs\Python\Python39\Lib\site-packages\askaway.wav"
The specified device is not open or is not recognized by MCI.
Failed to close the file: "C:\Users\jeandae\AppData\Local\Programs\Python\Python39\Lib\site-packages\askaway.wav"
Traceback (most recent call last):
File "C:/Users/jeandae/AppData/Local/Programs/Python/Python39/alarm 2.py", line 16, in <module>
playsound("C:\\Users\\jeandae\\AppData\\Local\\Programs\\Python\\Python39\\Lib\\site-packages\\askaway.wav")
File "C:\Users\jeandae\AppData\Local\Programs\Python\Python39\lib\site-packages\playsound.py", line 72, in _playsoundWin
winCommand(u'open {}'.format(sound))
File "C:\Users\jeandae\AppData\Local\Programs\Python\Python39\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 275 for command:
open "C:\Users\jeandae\AppData\Local\Programs\Python\Python39\Lib\site-packages\askaway.wav"
Cannot find the specified file. Make sure the path and filename are correct.
Give the play sound function the absolute path of the audio file ex:
playsound('C:/Users/user/Desktop/away.wav')
there is a problem with that package if you want you can use pydub which is more reliable than playsound.
Your code is okay and the problem is with the playsound it is not playing the audio. A very easy way to do so is.
import datetime
from pydub import AudioSegment
from pydub.playback import play
alarmHour = int(input("What hour do you want to wake up?"))
alarmMinute = int(input("What minute do you want?"))
amPm = str(input("Am or Pm")).lower().strip()
if (amPm == "pm"):
alarmHour = alarmHour + 12
while(1 == 1):
if(alarmHour == datetime.datetime.now().hour and
alarmMinute == datetime.datetime.now().minute):
print("Wake up, lazy!")
file1= AudioSegment.from_file("audiofile.wav")
play(file1)
break
print("Exited")
But you need to install pydub and you might face some error i recommend you read this article to properly install pydub.

How to play Audio in loop in Google colab

I ma trying to run the Audio in loop in google colab but it is not giving mi any output
from gtts import gTTS
from IPython.display import Audio
for voice in ["Aniket","sachin"]:
tts = gTTS("Hello {}".format(voice))
tts.save('1.wav')
sound_file = '1.wav'
Audio(sound_file, autoplay=True)
Output what I want is it should sound hello aniket hello sachin Pleas help
You only need to use "IPython.display.display" method as follows :
from gtts import gTTS
from IPython.display import Audio
from IPython.display import display
for voice in ["Aniket","sachin"]:
tts = gTTS("Hello {}".format(voice))
tts.save('1.wav')
sound_file = '1.wav'
wn = Audio(sound_file, autoplay=True) ##
display(wn)##
you can monkey patch audio to do it piggybacking on the autoplay:
a = Audio(...)
a.autoplay_attr = lambda: 'autoplay="autoplay" loop="loop"'

How to fix delays/lag in python script

I have my python script that executes an mp3 when the current time matches the time specified in a text file. However everything works well but I notice a lag and delay of around 18 seconds before mplayer plays the mp3 file.
Is there anyway of making my python script better in order to get rid of the 18 seconds lag and make the mp3 file play instantaneously?
Here is my python script:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# import libraries
import json
import urllib2
from bs4 import BeautifulSoup
import requests
import datetime
import playsound
import os
import subprocess
dateSTR = datetime.datetime.now().strftime('%H:%M')
f = open('/home/pi/test.txt','r')
messagetest = f.read()
newnametest = messagetest.replace("\n","")
f.close()
if (dateSTR) == (newnametest):
os.system("mplayer -ao alsa:device=bluealsa /home/pi/test.mp3")
Try starting mplayer in a subprocess before you actually need it as:
p = subprocess.Popen('mplayer -slave -idle -ao alsa:device=bluealsa', shell=True, stdin=subprocess.PIPE)
That should start up mplayer and have it waiting for when you need it. Then, when you want to play a file, do:
p.communicate(input=b'loadfile /home/pi/test.mp3\n')
I'd create a loop, something like:
from time import sleep
from datetime import datetime
...
done = []
while 1:
dateSTR = datetime.now().strftime('%H:%M')
if (dateSTR) == (newnametest) and not dateSTR in done:
done.append(dateSTR)
os.system("mplayer -ao alsa:device=bluealsa /home/pi/test.mp3")
sleep(1)

Python 3 permission error when playing a sound file (mp3, playsound module)

The program was working fine a few days ago, and it just stopped today. Not a single letter has been changed. One of my troubleshooting steps was to remove the file 'output1.mp3' and check if it will work that way, but it didn't. Another thing is that when it wasn't printing out the error, it would continue to play just this one sound file, whether or not it said the correct thing. Here's the latest error I got:
Traceback (most recent call last):
File "main3.py", line 123, in <module>
start()
File "main3.py", line 117, in start
tts(say)
File "main3.py", line 24, in tts
play('output1.mp3')
File "C:\Program Files (x86)\Python36-32\lib\site-packages\playsound.py", line 35, in _playsoundWin
winCommand('open "' + sound + '" alias', alias)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\playsound.py", line 31, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 275 for command:
open "output1.mp3" alias playsound_0.8842337577803419
Cannot find the specified file. Make sure the path and filename are correct.
Here's the code that I use:
import boto3 # used to 'pythonize' Amazon Polly TTS
import speech # speech recognition
from playsound import playsound as play # for playing sound files
import sys # basically only for exiting
# import locator # for determining the location of the user based on IP address
import locator2 # for confirming auto-detected location
# import locator3 # for definitely confirming auto-detection location
import question # module for answering any question
from datetime import datetime # for displaying the date and time
# from time import sleep # sleep (wai()t for) function
from os import popen as read # for reading command outputs "read('COMMAND').read()"
def tts(text):
polly = boto3.client("polly")
spoken_text = polly.synthesize_speech(Text=str(text),
OutputFormat='mp3',
VoiceId='Brian')
with open('output11.mp3', 'wb') as f:
f.write(spoken_text['AudioStream'].read())
f.close()
play('output11.mp3')
def ask(query):
question.question(query)
response = question.answer
print(response)
tts(response)
ai()
def time():
now = datetime.now()
print("Current date and time: ")
print(now.strftime("%H:%M") + "\n")
tts("It is " + now.strftime("%H:%M"))
ai()
def weather():
response = "Based on your IP address, I've detected that you're located in %s. Is that correct?" % locator2.city
print(response)
tts(response)
speech.speech()
if 'yes' in speech.x:
z = read('weather "%s"' % locator2.city).read()
print(z)
tts(z)
ai()
else:
response = 'Please say the name of the city you would like the weather information for. \n'
print(response)
tts(response)
speech.speech()
city = speech.x
wdr = read('weather "%s"' % city).read()
print(wdr)
tts(wdr)
ai()
def thank():
response = "You're very welcome! \n"
print(response)
tts(response)
ai()
def ext():
response = "Goodbye!"
print(response)
tts(response)
sys.exit()
def error():
response = "Invalid request detected, please try again...\n"
print(response)
tts(response)
ai()
def ai():
print('Started listening - Speak!')
speech.speech()
spoken = speech.x
# TODO new commands should be written above this, and their trigger words below :)
question_words = ['?', 'what', 'where', 'when', 'who', 'how', 'why']
if 'time' in spoken:
time()
elif 'weather' in spoken:
weather()
elif any(word in spoken for word in question_words):
ask(spoken)
elif 'thank' in spoken:
thank()
elif 'exit' or 'quit' or 'deactivate' in spoken:
ext()
else:
error()
def start():
say = "Hello! My name is Dave, and I'm your personal assistant. How may I help you today? \n"
print(say)
tts(say)
ai()
if __name__ == '__main__':
try:
start()
except KeyboardInterrupt:
ext()
The speech synthesizer is Amazon Polly. By the way, I was using PyCharm as an IDE and working on Windows 10. When I switch to my Linux machine the speech recognition part breaks.
UPDATE: I was tweaking the code a bit and managed to fix the pyaudio error, but I got another one in the process, this time it was about permissions. Here's the error log:
Traceback (most recent call last):
File "C:/Users/Despot/Desktop/DAv3/main3.py", line 123, in <module>
start()
File "C:/Users/Despot/Desktop/DAv3/main3.py", line 118, in start
ai()
File "C:/Users/Despot/Desktop/DAv3/main3.py", line 96, in ai
time()
File "C:/Users/Despot/Desktop/DAv3/main3.py", line 39, in time
tts("It is " + now.strftime("%H:%M"))
File "C:/Users/Despot/Desktop/DAv3/main3.py", line 21, in tts
with open('output11.mp3', 'wb') as f:
PermissionError: [Errno 13] Permission denied: 'output11.mp3'
UPDATE 2: I have been tikering about and I've found that the issue is only present on my Windows 10 machine, the program works fine on Linux.
Try using the absolute path (complete path) of the audio file instead of the relative path.
For example: "C:/Users/Adam/Desktop/dolphin.wav" instead of just "dolphin.wav"
This worked for me.
playsound libs has a windows directories in them.
If this fail only on Linux you should install playsound lib on the linux machine and then copy only the main3.py to it.
Answer for UPDATE2:
Copy output11.mp3 to another location and change the path to the new location:
with open('CHANGE-THIS-PATH', 'wb') as f:
Also make sure python run as administrator.
I solved this problem by moving the .py and .wav files to a folder less deep inside the file system.
I just renamed the audio file from sample.wav to sample
and then run it as playsound('sample.wav')
Luckily It ran.
Then I came to know that previously it was stored as sample.wav.wav.
So let's keep your audio file name as output.wav and try running your audio file as:
playsound('output.wav.wav') # or else rename it to output and run as
playsound('output.wav') # likewise for other audio formats too

Categories