I'm trying to take files from 'D:\Study\Progs\test\samples' and after transforming .wav to .png I want to save it to 'D:\Study\Progs\test\"input value"' but after "name = os.path.abspath(file)" program takes a wrong path "D:\Study\Progs\test\file.wav" not "D:\Study\Progs\test\samples\file.wav". What can I do this it? Here's my debug output And console output
import librosa.display
import matplotlib.pyplot as plt
import os
pa = "./"
save = pa+input()
os.mkdir(save)
for file in os.listdir("./samples"):
if file.endswith(".wav"):
print(file)
name = os.path.abspath(file)
ss = os.path.splitext(name)[0]+".png"
print(name)
audio = name
x, sr = librosa.load(audio, mono=True, duration=5)
save_path = os.path.join(save, ss)
X = librosa.stft(x)
Xdb = librosa.amplitude_to_db(abs(X))
plt.figure(figsize=(20, 10))
librosa.display.specshow(Xdb, sr=sr)
plt.savefig(save_path)
If you don't mind using pathlib
as @Andrew suggests, I think what you're trying to do could be accomplished by using the current working directory and the stem of each .wav file to construct the filename for your .png.
from pathlib import Path
cwd = Path.cwd() # Current path.
sample_dir = cwd / "samples" # Source files are here.
# Make some demo files if necessary.
if not sample_dir.exists():
sample_dir.mkdir()
(sample_dir / "file1.wav").touch() # Make empty demo file.
(sample_dir / "file2.wav").touch() # Make empty demo file.
for file in sample_dir.glob("*.wav"):
print(file)
outfile = (cwd / file.stem).with_suffix(".png")
print(f"->{outfile}")
pass # Replace this with whatever else needs to be done.