我正在尝试从 'D:\Study\Progs est\samples' 获取文件,并将 .wav 转换为 .png 后,我想将其保存到 'D:\Study\Progs est\"input value"' 但之后“name = os.path.abspath(file)”程序采用错误的路径“D:\Study\Progs est ile.wav”而不是“D:\Study\Progs est\samples ile.wav”。我能做什么呢?
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)
如果您不介意按照@Andrew的建议使用
pathlib
,我认为您可以通过使用当前工作目录和每个.wav文件的主干来构建.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.
这是我的替代工作变体
import librosa.display
import matplotlib.pyplot as plt
import os
from pathlib import Path
cwd = Path.cwd()
print("Vvedite directoriu dlya sohraneniya resultatov:")
sf = input()
save_folder = cwd / sf
print("Vvedite nazvanie directorii s primerami .wav failov:")
smpl = input()
sample_dir = cwd / smpl
os.mkdir(save_folder)
for file in sample_dir.glob("*.wav"):
print(file)
base = os.path.basename(file)
outfile = os.path.splitext(base)[0] + ".png"
print(f"->{outfile}")
audio = file
x, sr = librosa.load(audio, mono=True, duration=5)
save_path = os.path.join(save_folder, outfile)
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)