bash 循环执行“ffmpeg”命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21634088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:30:14  来源:igfitidea点击:

Execute "ffmpeg" command in a loop

bashffmpeg

提问by Mohammad Torfehnezhad

I have three .wavfiles in my folder and I want to convert them into .mp3with ffmpeg.

我的.wav文件夹中有三个文件,我想.mp3用 ffmpeg将它们转换成。

I wrote this bash script, but when I execute it, only the first one is converted to mp3.

我写了这个 bash 脚本,但是当我执行它时,只有第一个被转换为 mp3。

what should I do to make script keep going through my files?

我应该怎么做才能让脚本继续浏览我的文件?

This is the script:

这是脚本:

#!/bin/bash
find ./ -name "*.wav" -print | while read f
do
    name=${f:2:${#f}-6}
    cmd='ffmpeg -i "$name.wav" -ab 320k -ac 2 "$name.mp3"'
    eval $cmd
done

采纳答案by Reinstate Monica Please

No reason for find, just use bashwildcard globbing

无需查找,只需使用bash通配符通配符

#!/bin/bash
for name in *.wav; do
  ffmpeg -i "$name" -ab 320k -ac 2 "${name%.*}.mp3" 
done 

回答by Shammel Lee

Use the -nostdinflag in the ffmpeg command line:

-nostdin在 ffmpeg 命令行中使用该标志:

ffmpeg -nostdin -i "$name.wav" -ab 320k -ac 2 "$name.mp3"

See the -stdin/-nostdinflags in the ffmpeg documentation ? https://ffmpeg.org/ffmpeg.html

看到ffmpeg 文档中的-stdin/-nostdin标志了吗?https://ffmpeg.org/ffmpeg.html

回答by chepner

If you do need find(for looking in subdirectories or performing more advanced filtering), try this:

如果您确实需要find(用于查找子目录或执行更高级的过滤),请尝试以下操作:

find ./ -name "*.wav" -exec ffmpeg -i "{}" -ab 320k -ac 2 '$(basename {} wav)'.mp3 \;

Piping the output of findto the whileloop has two drawbacks:

将 的输出通过管道find传送到while循环有两个缺点:

  1. It fails in the (probably rare) situation where a matched filename contains a newline character.
  2. ffmpeg, for some reason unknown to me, will read from standard input, which interferes with the readcommand. This is easy to fix, by simply redirecting standard input from /dev/null, i.e. find ... | while read f; do ffmpeg ... < /dev/null; done.
  1. 它在匹配文件名包含换行符的(可能很少见)情况下失败。
  2. ffmpeg,出于某种我不知道的原因,将从标准输入读取,这会干扰read命令。这很容易解决,只需从 重定向标准输入/dev/null,即 find ... | while read f; do ffmpeg ... < /dev/null; done

In any case, don't store commands in variable names and evaluate them using eval. It's dangerous and a bad habit to get into. Use a shell function if you really need to factor out the actual command line.

在任何情况下,不要将命令存储在变量名中并使用eval. 进入它是危险的,也是一个坏习惯。如果您确实需要排除实际的命令行,请使用 shell 函数。