刚才需要将音乐转换为 ogg 格式以便能在欧卡中听歌,故做此记录
批处理的 for 循环
这里相当于一个 foreach 循环,关键词:for, in, do
batchfor /R %v in (*.mp3) do echo "%v"
上述语句会对递归(/R)后发现的所有 mp3 文件执行 echo 文件名操作。
对于循环,[这篇文章][1],可以参考。
批处理获得无扩展名的文件名
batch"%~nv"
其中 %v 是完整的 path,%~nv 就是所需文件名。
例子:
%v = C:\Users\i\Documents\Euro Truck Simulator 2\music\Rising Star\ 运命の轭.mp3
则 %~nv = 运命の轭
但是如果是递归目录,这样之后只能导出在一个目录。因此我们改用这种写法:
%r:~0,-5%
如果你对这种用法好奇,参考:[What is the best way to do a substring in a batch file?][2]
批处理一行写多个命令
&
[ref][2]
ffmpeg 转码
ffmpeg -i input.mp3 output.ogg
上述语句会把 input.mp3 转码为 ogg 格式,并保存为 output.ogg
写得比较好的是 [这篇文章][3],可以参考。
综合
由上,我们可以得到最终命令:
for /R %v in (*.mp3) do ffmpeg -i "%v" "%v:~0,-5%.ogg"
for /R %v in (.mp3) do set r="%v"& ffmpeg -i “%v” %r:~0,-5%.ogg" -b:a 128k
for /R %v in (.mp3) do set r="%v"& echo “!%r!”
最后,奉上 Python3 脚本
path = r"C:\Users\i\Documents\Euro Truck Simulator 2\music\Rising Star"
files = []
for r, d, f in os.walk(path):
for file in f:
if '.mp3' in file:
files.append(os.path.join(r, file))
for f in files:
newName = f[0:-4]+'.ogg'
print(newName)
os.system("ffmpeg -i \"{0}\" \"{1}\" -b:a 128k".format(f,newName))```
[1]: https://blog.csdn.net/u013514928/article/details/79629937
[2]: https://stackoverflow.com/questions/636381/what-is-the-best-way-to-do-a-substring-in-a-batch-file
[3]: https://blog.csdn.net/xuyankuanrong/article/details/77527381