Creating forks of `ffmpeg` in loop inside a shell

2019-08-11 09:54发布

I have a shell script that takes a directory as input, reads all mp4 files in it and convert them to a mp3 with ffmpeg:

#!/bin/bash

dir=$1

while read -rd "" file
do
  base=$(basename "$file")
  filename=${base%(*}".mp3"
  ffmpeg -i "$file" -vn -ar 44100 -ac 2 -ab 192000 -f mp3 "$filename" &
done < <(find $dir -maxdepth 1 -iname "*.mp4" -print0)

wait

exit 0

Currently all these calls to ffmpeg are forked because when I leave out the & at the end only the first file in converted and the others are ignored.

But this is problematic because somethings this fails on some files error messages like the following:

path/to/file/file name - with spaces(info)(temp_information).mp4: No such file or directory

All file names normally contain spaces, maybe that is the reason why it fails for some files.

Thus, I have the following questions:

  1. When I don't fork the ffmpeg calls why is only the first file executed? I expected that the loop waits until the process is finished and then continues with the next iteration.
  2. Why is the script unable to find some files (maybe it is a problem of ffmpeg)?
  3. How to solve all these problems and make the script to work?

1条回答
Juvenile、少年°
2楼-- · 2019-08-11 10:39

You are not acknowledging stdin

ffmpeg -i "$file" -blah -blah -nostdin "$filename" &

shell script ffmpeg stops after 2 jobs

To answer the comment:

You should not be forking anyway, FFmpeg already runs in multiple threads to maximize CPU, and you might even suffer from thrashing by forking it.

查看更多
登录 后发表回答