Bash script to convert samples to 16bit 44.1kHz mono with ffmpeg

Hi, I wrote a small script to help me convert lots of files to the internal format of the Play.

It overwrites the original samples, so take care, make backups, use at your own risk, etc :smiley:

It only converts the parameters which need to be converted, and doesn’t convert the samples at all, if they are already 16bit 44.1kHz mono.

You need to have mediainfo and ffmpeg installed.

#!/bin/bash

file="$1"
tmpfile="$(dirname "$1")/$(basename "${1%.*}")-tmp.wav"
channel="$(mediainfo "$1" | grep "Channel" | cut -d':' -f2 | cut -d' ' -f2)"
rate="$(mediainfo "$1" | grep "Sampling rate" | cut -d':' -f2 | cut -d' ' -f2)"
bit_depth="$(mediainfo "$1" | grep "Bit depth" | cut -d':' -f2 | cut -d' ' -f2)"

parameters=""

if [ "$channel" != "1" ]; then
  parameters="$parameters -ac 1"
fi

if [ "$rate" != "44.1" ]; then
  parameters="$parameters -ar 44100"
fi

if [ "$bit_depth" != "16" ]; then
  parameters="$parameters -sample_fmt s16"
fi

parameters="$(echo "$parameters" | xargs)"

if [ "$parameters" != "" ]; then
  ffmpeg -i "$file" $parameters "$tmpfile"
  mv "$tmpfile" "$file"
fi

I named the executable playconvert and put it in my $PATH.

This only converts a single sample, if you want to use it recursively, use it with find and the -exec option:

find . -iname *.wav -exec playconvert {} \;

I hope this will be useful for someone. Enjoy :smiley:

3 Likes
  • fix: channel detection not working when Channel layout is present in mediainfo
  • feat: run mediainfo only once to increase performance
#!/bin/bash

file="$1"
tmpfile="$(dirname "$1")/$(basename "${1%.*}")-tmp.wav"
info="$(mediainfo "$1")"
channel="$(echo "$info" | grep "Channel(s)" | cut -d':' -f2 | cut -d' ' -f2)"
rate="$(echo "$info" | grep "Sampling rate" | cut -d':' -f2 | cut -d' ' -f2)"
bit_depth="$(echo "$info" | grep "Bit depth" | cut -d':' -f2 | cut -d' ' -f2)"

parameters=""

if [ "$channel" != "1" ]; then
  parameters="$parameters -ac 1"
fi

if [ "$rate" != "44.1" ]; then
  parameters="$parameters -ar 44100"
fi

if [ "$bit_depth" != "16" ]; then
  parameters="$parameters -sample_fmt s16"
fi

parameters="$(echo "$parameters" | xargs)"

if [ "$parameters" != "" ]; then
  ffmpeg -i "$file" $parameters "$tmpfile"
  mv "$tmpfile" "$file"
fi