Search code examples
bashffmpegmetadata

convert metadata value to string while doing ffmpeg conversion


I have a script which splits mp3 files into smaller files and incrementally numbers them. I'm now also trying to incrementally increase the -metadata title number value and -metadata track number value but ffmpeg sees everything as a string. The line I'm having issue with is.

ffmpeg -i "$f" -f segment -segment_time 1200 -ar 22050 -ac 1 -metadata title="$%03d-$fn.mp3" -metadata track="$%02d" "$splitdirname/%03d-$fn.mp3" #split every 20mins

If you look at the metadata title created it says $%03d-title_of_file.mp3 I'm trying to get the metatdata title to increment like 001-title_of_file.mp3, 002-title_of_file.mp3, 003-title_of_file.mp3,...

The full script i'm using is below:

#!/bin/bash
#run using bash mp3spl.sh
currentdir="$(pwd)" #get current directory


for f in *.mp3 # only look for mp3 files
do

#fn=`echo "$1" | cut -d'.' -f1` #get just the filename no extension
fn=$(basename "$f" | cut -d'.' -f1) #get just the filename no extension
echo "($fn)"

splitdirname="$currentdir/split-$fn" #sub directory with correct names
#echo "splitdirname $splitdirname"
mkdir -p "$splitdirname" #make split directory
#echo "Processing $f"
ffmpeg -i "$1" 2> tmp.txt

ffmpeg -i "$f" -f segment -segment_time 1200 -ar 22050 -ac 1 -metadata title="$%03d-$fn.mp3" -metadata track="$%02d" "$splitdirname/%03d-$fn.mp3" #split every 20mins

#rm tmp.txt

done

Using -metadata title="$%03d-$fn.mp3" -metadata track="$%02d" does not create incremental numbers with leading zeros when used with ffmpeg.


Solution

  • The %03d syntax is only valid for input or output file patterns, for those (de)muxers that implement this kind of parsing (e.g., image2, segment). You cannot use it for setting metadata attributes. In other words, you can't have ffmpeg populate the field with the current segment filename.

    Also, the $ in $%03d does not make sense—you're not referring to a shell variable here.

    If you want to set the metadata according to the filename of the file that is generated, you have to do this in a second pass. Loop over each generated file, parse its filename, and use that to set the metadata value. Copy the existing audio/video streams with -c copy and -map 0 (the latter is necessary if you have more than one audio/video stream).