I am attempting to read different audio file formats from a folder using Python. The folder contains mainly .wav and .mp3 audio file formats. When I use the code listed below, I get the error:
Traceback (most recent call last): File
"G:/FAU/PythonCode/scipy_audio_spectrogram.py", line 7, in <module>
fs, Audiodata = wavfile.read(AudioName) File "C:\Python\lib\site-packages\scipy\io\wavfile.py", line 267, in read
file_size, is_big_endian = _read_riff_chunk(fid) File "C:\Python\lib\site-packages\scipy\io\wavfile.py", line 168, in
_read_riff_chunk
"understood.".format(repr(str1))) ValueError: File format b'ID3\x03'... not understood.
How to modify the code so that both .wav and .mp3 files can be read from the folder? Thanks!
Here is the code that I am using:
from scipy.io import wavfile # scipy library to read wav files
import numpy as np
AudioName = r'G:\FAU\PythonCode\4201.mp3' # Audio File
fs, Audiodata = wavfile.read(AudioName)
Related
I am trying to read s2p files in using Python scikit-rf library. The s2p file in not in S parameter. I converted it to Z parameter. Looks like scikit-rf can read only S parameter file. Is there any other library or way to read s2p files with Z parameter. Below is how I am reading the file:
import skrf as rf
ntwk = rf.Network('ZTEST5_SHORTED.s10p')
s = ntwk.s
print(s)
Below is the error:
Traceback (most recent call last):
File "C:\Users\pujai\PycharmProjects\SIIntegration\practice.py", line 26, in <module>
ntwk = rf.Network('ZTEST5_SHORTED_DCfitted.s10p')
File "C:\Users\pujai\PycharmProjects\SIIntegration\venv\lib\site-packages\skrf\network.py", line 457, in __init__
self.read_touchstone(filename, self.encoding)
File "C:\Users\pujai\PycharmProjects\SIIntegration\venv\lib\site-packages\skrf\network.py", line 2050, in read_touchstone
raise NotImplementedError('only s-parameters supported for now.')
NotImplementedError: only s-parameters supported for now.
If I try to read an S parameter file, it works fine. Any help?
I'm using WAVIO python API to write data to a .wav file.
In order to test this api, First I read data .wav file and then I want to generate .wav containing the same data of the input .wav file, but I got an error while writing data to the output wav file.
import numpy as np
import wavio
wa = wavio.read("s24.wav") #Read a .wav file
print("x= "+str(wa.data)) #Data
print("rate= "+str(wa.rate)) #Rate
print("sampwidth= "+str(wa.sampwidth)) #sampwidth
wavio.write("sine24_output", wa.data, wa.rate,wa.sampwidth) #Error is here
Error is:
Traceback (most recent call last):
File "C:/Users/user/Desktop/Wav2Bytes/wavii.py", line 24, in <module>
wavio.write("sine24_output", wa.data, wa.rate,wa.sampwidth) #Write a .wav file. Error is here
File "C:\Program Files (x86)\Python\lib\site-packages\wavio.py", line 363, in write
vmin, vmax = scale
TypeError: cannot unpack non-iterable int object
You are missing the argument's name sampwidth. According to the docs, there are 5 arguments, if you don't specify the name sampwidth, it will instead set scale to wa.sampwidth. Anyway just use this:
wavio.write("sine24_output", wa.data, wa.rate,sampwidth=wa.sampwidth)
I am trying to read a h5 file in Python.
The file can be found in this link and it is called 'vstoxx_data_31032014.h5'. The code I am trying to run is from the book Python for Finance, by Yves Hilpisch and goes like this:
import pandas as pd
h5 = pd.HDFStore('path.../vstoxx_data_31032014.h5', 'r')
futures_data = h5['futures_data'] # VSTOXX futures data
options_data = h5['options_data'] # VSTOXX call option data
h5.close()
I am getting the following error:
h5 = pd.HDFStore('path.../vstoxx_data_31032014.h5', 'r')
Traceback (most recent call last):
File "<ipython-input-692-dc4e79ec8f8b>", line 1, in <module>
h5 = pd.HDFStore('path.../vstoxx_data_31032014.h5', 'r')
File "C:\Users\Laura\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 466, in __init__
self.open(mode=mode, **kwargs)
File "C:\Users\Laura\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 637, in open
raise IOError(str(e))
OSError: HDF5 error back trace
File "C:\aroot\work\hdf5-1.8.15-patch1\src\H5F.c", line 604, in H5Fopen
unable to open file
File "C:\aroot\work\hdf5-1.8.15-patch1\src\H5Fint.c", line 1085, in H5F_open
unable to read superblock
File "C:\aroot\work\hdf5-1.8.15-patch1\src\H5Fsuper.c", line 277, in H5F_super_read
file signature not found
End of HDF5 error back trace
Unable to open/create file 'path.../vstoxx_data_31032014.h5'
where I have substituted my working directory for 'path.../' for the purpose of this question.
Does anyone know where this error might be coming from?
In order to open a HDF5 file with the h5py module you can use h5py.File(filename). The documentation can be found here.
import h5py
filename = "vstoxx_data_31032014.h5"
h5 = h5py.File(filename,'r')
futures_data = h5['futures_data'] # VSTOXX futures data
options_data = h5['options_data'] # VSTOXX call option data
h5.close()
import os
wd=os.chdir('pah of your working directory') #change the file path to your working directory
wd=os.getcwd() #request what is the current working directory
print(wd)
if __name__ == '__main__':
# import required libraries
import h5py as h5
import numpy as np
import matplotlib.pyplot as plt
f = h5.File("hdf5 file with its path", "r")
datasetNames = [n for n in f.keys()]
for n in datasetNames:
print(n)
I try to open a wave file with the wave module, but I keep getting the same error whatever I try.
The line with the error is the following:
wav = wave.open(f)
This is the error message:
Traceback (most recent call last):
File "annotate.py", line 47, in <module>
play(file)
File "annotate.py", line 33, in play
wav = wave.open(f)
File "C:\Program Files (x86)\Python\lib\wave.py", line 498, in open
return Wave_read(f)
File "C:\Program Files (x86)\Python\lib\wave.py", line 163, in __init__
self.initfp(f)
File "C:\Program Files (x86)\Python\lib\wave.py", line 143, in initfp
self._read_fmt_chunk(chunk)
File "C:\Program Files (x86)\Python\lib\wave.py", line 269, in _read_fmt_chunk
raise Error('unknown format: %r' % (wFormatTag,))
wave.Error: unknown format: 49
String f is a path to a .WAV file and it works when played in any of my media players.
I have of course imported the wave module.
I tried f both as a relative and an absolute path.
I tried replacing "WAV" by "wav".
What is the error caused by?
Python's wave module works with a specific type of WAV: PCM (WAVE_FORMAT_PCM: 0x0001).
In your case, you're using a WAV of type WAVE_FORMAT_GSM610 [0x0031 = hex(49)].
You can use a program like Audacity or some lib for converting codecs to change the type of the WAV file.
You can see a list of WAV types here:
https://www.videolan.org/developers/vlc/doc/doxygen/html/vlc__codecs_8h.html
Python's wave module source code:
https://github.com/python/cpython/blob/master/Lib/wave.py
The file is compressed and the wave module does not support this type of compression.
I'm looking for a way to open and crop several tiff images and then save the new croped images created in the same folder (related to my script folder).
My current code looks like this:
from PIL import Image
import os,platform
filespath = os.path.join(os.environ['USERPROFILE'],"Desktop\Python\originalImagesfolder")
for file in os.listdir(filespath):
if file.endswith(".tif"):
im = Image.open(file)
im.crop((3000, 6600, 3700, 6750)).save(file+"_crop.tif")
This script is returning me the error:
Traceback (most recent call last):
File "C:\Users...\Desktop\Python\script.py", line 22, in
im = Image.open(file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 2219, in open
fp = builtins.open(fp, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Image1Name.tif'
'Image1Name.tif' is the first tif image I'm trying to process in the folder. I don't get how the script can give the file's name without being able to find it. Any Help?
PS: I have 2 days experience in python and codes generaly speaking. Sorry if the answer is obvious
[EDIT/Update]
After modifying my initial code thanks to vttran and ChrisGuest answers, turning then into this:
from PIL import Image
import os,platform
filespath = os.path.join(os.environ['USERPROFILE'],"Desktop\Python\originalImagesfolder")
for file in os.listdir(filespath):
if file.endswith(".tif"):
filepath = os.path.join(filespath, file)
im = Image.open(filepath)
im.crop((3000, 6600, 3700, 6750)).save("crop"+file)
the script is returning me a new error message:
Traceback (most recent call last):
File "C:/Users/.../Desktop/Python/script.py", line 11, in
im.crop((3000, 6600, 3700, 6750)).save("crop"+file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 986, in crop
self.load()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 166, in load
self.load_prepare()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 250, in
load_prepare
self.im = Image.core.new(self.mode, self.size) ValueError: unrecognized mode
A maybe-useful information, it's a Landsat8 image in GeoTiff format. The TIFF file therefore include geoposition, projection... informations. The script works perfectly fine if I first open and re-save them with a software like Photoshop (16int tiff format).
When you are search for the file names you use filespath to specify the directory.
But then when you open the file, you are only using the base filename.
So you could replace
im = Image.open(file)
with
filepath = os.path.join(filespath, file)
im = Image.open(filepath)
Also consider using the glob module, as you can do glob.glob(r'path\*.tif) .
It is also good practice to avoid using builtin functions like file as variable names.