I am trying the gTTS (Google Text To Speach) function in python, saving the mp3 file works (the file is being saved and can be played).
Now I am trying to play the file directly with the below code, but it is throwing an error
Code:
import gtts
import pyglet
import os
import time
text = ("Hello World")
obj = gtts.gTTS(text=text, lang='en')
speech_filename = 'c:/test_voice.mp3'
obj.save(speech_filename)
print("Play sound...")
music = pyglet.media.load(speech_filename, streaming=False)
music.play
sleep.time(music.duration) #prevent from killing
os.remove(speech_filename) #remove temp file
Error:
Traceback (most recent call last):
File "C:\python\text-to-speach.py", line 16, in
music = pyglet.media.load(speech_filename, streaming=False)
File "C:\Python\lib\site-packages\pyglet\media\sources\loader.py", line 63, in load
source = get_source_loader().load(filename, file)
File "C:\Python\lib\site-packages\pyglet\media\sources\loader.py", line 84, in load
return WaveSource(filename, file)
File "C:\Python\lib\site-packages\pyglet\media\sources\riff.py", line 200, in init
'AVbin is required to decode compressed media')
pyglet.media.sources.riff.WAVEFormatException: AVbin is required to decode compressed media
it is looking for AVbin,
check following would help you
https://stackoverflow.com/questions/10302873/python-pyglet-avbin-how-to-install-avbin
Ok so this is how I solved it, I also added a delay loop that waits for the audio file to finish and delete it afterwards.
import gtts
import pygame
#install pyglet and install http://avbin.github.io/AVbin/Download.html
#extract the avbin.dll from windows/system32/ folder to windows/system/ folder
import os
import time
pygame.mixer.init()
text = ("Hello, World")
obj = gtts.gTTS(text=text, lang='en')
speech_filename = "c:/python/code/test_voice.mp3"
obj.save(speech_filename)
print("Play sound...")
pygame.mixer.music.load(speech_filename)
pygame.mixer.music.play()
busy = True
while busy == True:
if pygame.mixer.music.get_busy() == False:
busy = False
pygame.quit()
os.remove(speech_filename) #remove temp file - remove line to keep file
Related
I'm trying to create a text file with a tree of all files / dirs from a place that I choose using os.chdir(). My approach is to print the tree and to save all prints to the text file. The problem is that it doesn't copy the printed tree and the file is blank.
What am I doing wrong?
And is there a way to write this kind of data to the file without to actually print it?
My code:
import os
import sys
f = open("tree.txt", "w")
os.chdir("c:\\Users\Daniel\Desktop")
sys.stdout = f
os.system("tree /f")
f.close()
Edit
I was able to get the file tree from the clipboard after executing the command, however it gives me and eror when it tried to write to the txt file.
code:
import os
import tkinter
with open("tree.txt", "w") as f:
os.system("tree /f |clip")
root = tkinter.Tk()
tree = root.clipboard_get()
print(tree)
f.write(tree)
eror:
Traceback (most recent call last):
File "c:\Users\Daniel\Desktop\Tick\code_test\files.py", line 9, in <module>
f.write(tree)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2502' in position 80: character maps to <undefined>
solution
So I found the problem, I needed to use codec to be able write unicode to the text file. Now it works very well
code:
import os
import tkinter
import codecs
with codecs.open("tree.txt", "w", "utf8") as f:
os.chdir("c:\\Users")
os.system("tree /f |clip")
root = tkinter.Tk()
tree = root.clipboard_get()
f.write(tree)
Method check_output from subprocess module can help you to catch program output:
import subprocess
f = open("tree.txt", "wb")
tree_output = subprocess.check_output('tree /f', shell=True, cwd=r'c:\Users\Daniel\Desktop')
f.write(tree_output)
f.close()
Or with context manager:
import subprocess
with open("tree.txt", "wb") as f:
f.write(subprocess.check_output('tree /f', shell=True, cwd=r'c:\Users\Daniel\Desktop'))
Option wb is required because check_output returns bytes not a str. If you want to process output like a string - call tree_output.decode() first.
I am making a game, and I need to load some password protected audio files from a .zip file, but I get this error:
io.UnsupportedOperation: seek
io.UnsupportedOperation: seek
io.UnsupportedOperation: seek
b'hey you did it!' #THIS IS FROM THE PROGRAM
Traceback (most recent call last):
File "C:\Python36\lib\zipfile.py", line 849, in read
data = self._read1(n)
File "C:\Python36\lib\zipfile.py", line 917, in _read1
data += self._read2(n - len(data))
File "C:\Python36\lib\zipfile.py", line 949, in _read2
data = self._fileobj.read(n)
File "C:\Python36\lib\zipfile.py", line 705, in read
self._file.seek(self._pos)
AttributeError: 'NoneType' object has no attribute 'seek'
And this is my code below:
from zipfile import ZipFile
from PIL import Image
from io import BytesIO
import pygame
from pygame.locals import *
import pyganim
import sys
pygame.init()
root = pygame.display.set_mode((320, 240), 0, 32)
pygame.display.set_caption('image load test')
#THIS IS HOW TO LOAD IMAGES (WORKS)
with ZipFile("spam.zip", 'r') as archive:
mcimg = archive.read('a.png', pwd=b'onlyforthedev')
mc = pygame.image.load(BytesIO(mcimg))
anime = pyganim.PygAnimation([(mc, 100),
(mc, 100)])
anime.play()
#THIS IS HOW TO LOAD MUSIC (DOES NOT WORK)
with ZipFile('spam.zip') as zippie:
with zippie.open('zora.mp3', pwd=b'onlyforthedev') as zora:
pygame.mixer.music.load(zora)
pygame.mixer.music.play(-1)
#THIS IS HOW TO LOAD TEXT (WORKS)
with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt', pwd=b'onlyforthedev') as myfile:
print(myfile.read())
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
root.fill((100, 50, 50))
anime.blit(root, (100, 50))
pygame.display.update()
What can I do to load sound files without raising such an error? And what is 'seek'?
I also get this error on python 3.6.
I am going to guess that pygame.mixer.music.load calls the seek method on zippie, which is a ZipExtFile.
From python 3.7 ZipExtFile objects now have a seek method. I think that if you upgrade to python 3.7.2 or newer, then your error should go away.
Try to replace
pygame.mixer.music.load(zora)
with
with BytesIO(zora.read()) as zora_bio:
pygame.mixer.music.load(zora_bio)
This worked for me on python 3.6 with h5py.File().
I'm guessing it's the same problem as with pygame..load().
EDIT:
I now realize the above solution already exists in your code when you LOAD IMAGES:
with ZipFile("spam.zip", 'r') as archive:
mcimg = archive.read('a.png', pwd=b'onlyforthedev')
mc = pygame.image.load(BytesIO(mcimg))
So for uniformity, you could LOAD MUSIC in a similar way:
with ZipFile('spam.zip') as zippie:
zora = zippie.read('zora.mp3', pwd=b'onlyforthedev')
pygame.mixer.music.load(BytesIO(zora))
I have images in the same directory with a python file, i am trying to loop over the images and convert them into base64 but am getting this error.
Am using Ubuntu 14.0.4
Traceback (most recent call last):
File "convert_to_base64.py", line 33, in <module>
print(main())
File "convert_to_base64.py", line 26, in main
convert_to_base64()
File "convert_to_base64.py", line 19, in convert_to_base64
with open("*.jpg", "rb") as f:
IOError: [Errno 2] No such file or directory: '*.jpg'
Here is my python code
# -*- coding: utf-8 -*-
import os
import sys
import xlrd
import base64
import urllib
from datetime import datetime
reload(sys) # to re-enable sys.setdefaultencoding()
sys.setdefaultencoding('utf-8')
def convert_to_base64():
"""
Read all jpg images in a folder,
and print them in base64
"""
with open("*.jpg", "rb") as f:
data = base64.b64decode(f.read())
print data
def main():
start_datetime = datetime.now()
convert_to_base64()
end_datetime = datetime.now()
print '------------------------------------------------------'
print 'Script started : {}'.format(start_datetime)
print 'Script finished: {}'.format(end_datetime)
if __name__ == '__main__':
print(main())
print('Done')
someone help me figure out what am doing wrong.
Thanks
This is how I looped for images in a directory:
import os
pictures = []
for file in os.listdir("pictures"):
if file[-3:].lower() in ["png"]:
pictures.append(file)
Please refer to Python documentation https://docs.python.org/2/tutorial/inputoutput.html for more info on open() function:
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).
I'm trying to write a simple script to merge two PDFs but have run into an issue when trying to save the output to disk. My code is
from PyPDF2 import PdfFileWriter, PdfFileReader
import tkinter as tk
from tkinter import filedialog
### Prompt the user for the 2 files to use via GUI ###
root = tk.Tk()
root.update()
file_path1 = tk.filedialog.askopenfilename(
filetypes=[("PDF files", "*.pdf")],
)
file_path2 = tk.filedialog.askopenfilename(
filetypes=[("PDF files", "*.pdf")],
)
###Function to combine PDFs###
output = PdfFileWriter()
def append_pdf_2_output(file_handler):
for page in range(file_handler.numPages):
output.addPage(file_handler.getPage(page))
#Actually combine the 2 PDFs###
append_pdf_2_output(PdfFileReader(open(file_path1, "rb")))
append_pdf_2_output(PdfFileReader(open(file_path2, "rb")))
###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfile(
defaultextension='pdf')
###Write the output to disk###
output.write(output_name)
output.close
The problem is that I get an error of
UserWarning: File to write to is not in binary mode. It may not be written to correctly. [pdf.py:453] Traceback (most recent call last): File "Combine2Pdfs.py", line 44, in output.write(output_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PyPDF2/pdf.py", line 487, in write stream.write(self.header + b("\n")) TypeError: write() argument must be str, not bytes
Where have I gone wrong?
I got it by adding mode = 'wb' to tk.filedialog.asksaveasfile. Now it's
output_name = tk.filedialog.asksaveasfile(
mode = 'wb',
defaultextension='pdf')
output.write(output_name)
Try to use tk.filedialog.asksaveasfilename instead of tk.filedialog.asksaveasfile. You just want the filename, not the file handler itself.
###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfilename(defaultextension='pdf')
When I run my program, I get the following error and am not sure on how to correct it. Can someone help with explaining what this error is and how to correct it? Newb here so details are appreciated. Thanks for your time in advance!
Code:
#!/usr/bin/python
import zipfile
from PySide import QtGui
import re
#Select file to extract
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.AnyFile)
if (dialog.exec()):
fileName = dialog.selectedFiles()
#Select Directory to extract to
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
if (dialog.exec()):
dirName = dialog.selectedFiles()
print("Extracting.....")
zFile= zipfile.ZipFile(fileName)
zFile.extractall(dirName)
Error output:
Traceback (most recent call last):
File "C:\Users\Jennifer\Documents\BatchScripts\unzip.py", line 22, in <module>
zFile= zipfile.ZipFile(fileName)
File "C:\Python33\lib\zipfile.py", line 933, in __init__
self._RealGetContents()
File "C:\Python33\lib\zipfile.py", line 970, in _RealGetContents
endrec = _EndRecData(fp)
File "C:\Python33\lib\zipfile.py", line 237, in _EndRecData
fpin.seek(0, 2)
AttributeError: 'list' object has no attribute 'seek'
In your file and target directory code blocks, dialog.selectedFiles() returns a list. zipfile.ZipFile can only handle one file at a time, hence your error. To iterate over the list being provided by dialog.selectedFiles(), use the following:
for archive in fileName: # you should probably change it to fileNames to reflect its true nature
zfile = zipfile.ZipFile(archive)
print("Extracting " + str(zfile.filename) + "...")
zfile.extractall(dirName[0]) # also a list, extract to first item and ignore rest
and you should be all set.