I'm trying to use pydub for a music project, but when trying to play sounds with this chunk of code
from pydub import AudioSegment
from pydub.playback import play
sound = AudioSegment.from_wav("s1.wav")
play(sound)
i get the following error:
RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
C:\Python\Python385\lib\site-packages\pydub\utils.py:184: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "C:/Users/vicen/Desktop/music project/mian.py", line 6, in <module>
play(s1)
File "C:\Python\Python385\lib\site-packages\pydub\playback.py", line 74, in play
_play_with_ffplay(audio_segment)
File "C:\Python\Python385\lib\site-packages\pydub\playback.py", line 18, in _play_with_ffplay
seg.export(f.name, "wav")
File "C:\Python\Python385\lib\site-packages\pydub\audio_segment.py", line 809, in export
out_f, _ = _fd_or_path_or_tempfile(out_f, 'wb+')
File "C:\Python\Python385\lib\site-packages\pydub\utils.py", line 60, in _fd_or_path_or_tempfile
fd = open(fd, mode=mode)
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\vicen\\AppData\\Local\\Temp\\tmpvwotqts5.wav'
Does someone understand why it isn't working? I am fairly new to python so i don't.
The python script encountered a Permission Error
It is trying to read 'C:\\Users\\vicen\\AppData\\Local\\Temp\\tmpvwotqts5.wav'
file but doesn't have permission to write in the directory.
Changing permissions on the above mentioned Temp folder should solve the problem.
Or you could run your python script using sudo command. Since you are using windows this should help in this regard.
Easy Fix from here:
pip install simpleaudio
Pydub uses tempfiles extensively .As suggested here you can add TMPDIR environment variable.
the problem is with the tempfile , as mentioned here
so the file playback.py , which is one of the files of this pydub module (you may find it at Python\Python-version-\Lib\site-packages\pydub ) , must be modified.
there are two recommended methods to solve this,
mentioned here
create a custom tempfile like below at playback.py
`
import subprocess
from tempfile import NamedTemporaryFile
from .utils import get_player_name, make_chunks
import random
import os
import tempfile
class CustomNamedTemporaryFile:
"""
This custom implementation is needed because of the following limitation of tempfile.NamedTemporaryFile:
> Whether the name can be used to open the file a second time, while the named temporary file is still open,
> varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
"""
def __init__(self, mode='wb', delete=True, suffix = ''):
self._mode = mode
self._delete = delete
self.suffix = suffix
def __enter__(self):
# Generate a random temporary file name
file_name = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())
# Ensure the file is created
open(file_name+self.suffix, "x").close()
# Open the file in the given mode
self._tempFile = open(file_name+self.suffix, self._mode)
return self._tempFile
def __exit__(self, exc_type, exc_val, exc_tb):
self._tempFile.close()
if self._delete:
os.remove(self._tempFile.name)
def _play_with_ffplay(seg):
PLAYER = get_player_name()
# with NamedTemporaryFile("w+b", suffix=".wav") as f:
with CustomNamedTemporaryFile(mode='wb', suffix = ".wav") as f:
seg.export(f.name, "wav")
subprocess.call([PLAYER, "-nodisp", "-autoexit", "-hide_banner", f.name])
'
Related
I am creating an app based on speech. Everything works fine but I do not want my app to use outside program to open mp3 file. At the moment program can do several commands only if I will use: cmd
def speak(text):
tts = gTTS(text=text, lang='pl')
filename = 'speak.mp3'
tts.save(filename)
cmd = filename #works for several commands with external program
os.system(cmd)
What I would like to do is something like this:
def speak(text):
tts = gTTS(text=text, lang='pl')
filename = 'speak.mp3'
tts.save(filename)
playsound.playsound(filename)
return speak
Unfortunately it works only for first audio input, second one gives error:
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\gtts\tts.py", line 294, in save
with open(str(savefile), 'wb') as f:
PermissionError: [Errno 13] Permission denied: 'speak.mp3'
I was trying to delete mp3 file after it has been saved and played but it did not helped.
Any idea how to solve it?
Try to see the permissions of the file that has been created. It might have only read permissions.
When passing in the function, attempt to supply various file names for each of the distinct texts, or use the random.randit() method to set different file names, or use the current time as your file name using the time module.
I am learning Python and related modules. Here are my scripts.
import tarfile
from six.moves import urllib
data_path = "./datasets/housing/"
file = "housing.tgz"
data_path_file = data_path + file
tar_file = tarfile.open(data_path_file)
# tested following script, failed
tar_file = tarfile.open(data_path_file,'r')
# end test
tar_file.extractall(path=data_path_file)
I hope my scripts can unzip the tgz file and write into a new file. I always received following error messages:
raise ReadError("file could not be opened successfully")
tarfile.ReadError: file could not be opened successfully
I checked the path and file name. No errors exist. Any correction and further help would be highly appreciated.
I'm currently trying to write a simple Python (3.6.6) program that can grab a Youtube video, play it back, and graph the waveplot and spectogram of the file. But it only runs properly in Jupyter notebook. I'm using this site as a guide on the program. I want to make sure it can run in IDLE as well, but so far no luck. Here's the code section regarding the file retrieval / path set and trying to play it back:
# Downloading audio
audiostream = video.getbestaudio()
# audiostream.download()
from tkinter import filedialog as fd
# Asking where to save it
print("Select the directory...")
dir_name = fd.askdirectory()
print(dir_name)
path = dir_name + "/" + video.title + ".wav"
print(path)
audiofile = audiostream.download(filepath=path)
import IPython.display as ipd
# Playing back the audio
print("Playing back audio...")
ipd.Audio(filename=path)
And the error message:
Traceback (most recent call last):
File "C:\Users\(myPCname)\Desktop\YTpyDwnlder.py", line 45, in <module>
ipd.Audio(filename=path)
File "C:\Python36\lib\site-packages\IPython\lib\display.py", line 110, in __init__
super(Audio, self).__init__(data=data, url=url, filename=filename)
File "C:\Python36\lib\site-packages\IPython\core\display.py", line 627, in __init__
self.reload()
File "C:\Python36\lib\site-packages\IPython\lib\display.py", line 121, in reload
super(Audio, self).reload()
File "C:\Python36\lib\site-packages\IPython\core\display.py", line 652, in reload
with open(self.filename, self._read_flags) as f:
OSError: [Errno 22] Invalid argument: 'C:/Users/(myPCname)/Desktop/gui/Low Roar - "I\'ll Keep Coming".wav'
The path seems correct for the most part so I'm not sure why the program thinks it's wrong. I've tried to double and triple check through looking up other sites on Python string formatting for files and I can't find what's wrong. I've also tried inserting '\' to all potential single or double quotes within (provided they don't already have the '\' before them) the string but it still doesn't like it (I know this is a futile attempt and is redundant).
How can I fix this?
Also sorry if the tags are incorrect; this is my first time posting a question on here.
Nevermind. I found that the problem was due to invalid characters in the filename ('"' is changed to '#' in the filename).
I am attempting to create and write to a temporary file on Windows OS using Python. I have used the Python module tempfile to create a temporary file.
But when I go to write that temporary file I get an error Permission Denied. Am I not allowed to write to temporary files?! Am I doing something wrong? If I want to create and write to a temporary file how should should I do it in Python? I want to create a temporary file in the temp directory for security purposes and not locally (in the dir the .exe is executing).
IOError: [Errno 13] Permission denied: 'c:\\users\\blah~1\\appdata\\local\\temp\\tmpiwz8qw'
temp = tempfile.NamedTemporaryFile().name
f = open(temp, 'w') # error occurs on this line
NamedTemporaryFile actually creates and opens the file for you, there's no need for you to open it again for writing.
In fact, the Python docs state:
Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
That's why you're getting your permission error. What you're probably after is something like:
f = tempfile.NamedTemporaryFile(mode='w') # open file
temp = f.name # get name (if needed)
Use the delete parameter as below:
tmpf = NamedTemporaryFile(delete=False)
But then you need to manually delete the temporary file once you are done with it.
tmpf.close()
os.unlink(tmpf.name)
Reference for bug: https://github.com/bravoserver/bravo/issues/111
regards,
Vidyesh
Consider using os.path.join(tempfile.gettempdir(), os.urandom(24).hex()) instead. It's reliable, cross-platform, and the only caveat is that it doesn't work on FAT partitions.
NamedTemporaryFile has a number of issues, not the least of which is that it can fail to create files because of a permission error, fail to detect the permission error, and then loop millions of times, hanging your program and your filesystem.
The following custom implementation of named temporary file is expanded on the original answer by Erik Aronesty:
import os
import tempfile
class CustomNamedTemporaryFile:
"""
This custom implementation is needed because of the following limitation of tempfile.NamedTemporaryFile:
> Whether the name can be used to open the file a second time, while the named temporary file is still open,
> varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
"""
def __init__(self, mode='wb', delete=True):
self._mode = mode
self._delete = delete
def __enter__(self):
# Generate a random temporary file name
file_name = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())
# Ensure the file is created
open(file_name, "x").close()
# Open the file in the given mode
self._tempFile = open(file_name, self._mode)
return self._tempFile
def __exit__(self, exc_type, exc_val, exc_tb):
self._tempFile.close()
if self._delete:
os.remove(self._tempFile.name)
This issue might be more complex than many of you think. Anyway this was my solution:
Make use of atexit module
def delete_files(files):
for file in files:
file.close()
os.unlink(file.name)
Make NamedTemporaryFile delete=False
temp_files = []
result_file = NamedTemporaryFile(dir=tmp_path(), suffix=".xlsx", delete=False)
self.temp_files.append(result_file)
Register delete_files as a clean up function
atexit.register(delete_files, temp_files)
tempfile.NamedTemporaryFile() :
It creates and opens a temporary file for you.
f = open(temp, 'w') :
You are again going to open the file which is already open and that's why you are getting Permission Denied error.
If you really wants to open the file again then you first need to close it which will look something like this-
temp= tempfile.NamedTemporaryFile()
temp.close()
f = open(temp.name, 'w')
Permission was denied because the file is Open during line 2 of your code.
close it with f.close() first then you can start writing on your tempfile
I'm attempting to write a very simple script that counts the number of entries/files a given ZIP file has, for some statistics.
I'm using the zipfile library, and I'm running into this problem where the library appears not to support .zipx format.
bash-3.1$ python zipcount.py t.zipx
Traceback (most recent call last):
File "zipcount.py", line 10, in <module>
zipCount(file)
File "zipcount.py", line 5, in zipCount
with ZipFile(file, "r") as zf:
File "c:\Python34\lib\zipfile.py", line 937, in __init__
self._RealGetContents()
File "c:\Python34\lib\zipfile.py", line 978, in _RealGetContents
raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file
Googling for help reveals that the zipx format is not the same as zip, and so maybe I shouldn't be expecting this to work. Further googling though fails to bring up a library that actually can deal with zipx. Searching stack overflow didn't find much either.
I can't possibly be the only person who wants to manipulate zipx files in python, right? Any suggestions?
chilkat might work for this. It's not a free library but there is a 30 day trial. Here is an example from http://www.example-code.com/python/ppmd_compress_file.asp:
import sys
import chilkat
compress = chilkat.CkCompression()
# Any string argument automatically begins a 30-day trial.
success = compress.UnlockComponent("30-day trial")
if (success != True):
print "Compression component unlock failed"
sys.exit()
compress.put_Algorithm("ppmd")
# Decompress back to the original:
success = compress.DecompressFile("t.zipx", "t")
if (success != True):
print compress.lastErrorText()
sys.exit()
print "Success!"
The API documentation: http://www.chilkatsoft.com/refdoc/pythonCkCompressionRef.html
There is no direct python package to unzip the zipx files in python.
So, One simple way to unzip it is using subprocess and winzip application. Please find the below code.
import subprocess
command = "C:\Program Files\WinZip\wzunzip.exe" "D:\Downloads\hello.zipx" "D:\unzip_location"
subprocess.run(command, shell=True, timeout=120)