NAS-Script: Converteren naar MP3 – Versie 1.2

Status: Verouderd, versie 1.3 is beschikbaar.

Beschrijving

Script voor het converteren van je hoge kwaliteit muziekbibliotheek (mogen zowel FLAC en MP3 bestanden zijn) naar een lagere kwaliteit (MP3 met variable bitrate). Bestaande MP3 bestanden worden alleen gekopieerd, niet geconverteerd.

Persoonlijk gebruik ik dit om mijn volledige muziekbibliotheek (bestaat origineel voor 99% uit FLAC bestanden) te kunnen syncen met de harde schijf in de auto en naar de SD-kaart in mijn telefoon (voor beiden is deze geluidskwaliteit ruim voldoende).

Update

Onderstaand de uitbreiding op de vorige versie van het script; de bestanden folder.jpg (normaal gesproken de afbeelding van het album) in de muziekfolders worden nu mee gekopieerd.

Code

# Script to convert FLAC-files in one folder to MP3 in another folder, or copy the file if the original file is already MP3.
# Install FFMPEG on Synology NAS via package from https://synocommunity.com/package/ffmpeg

/usr/syno/bin/synologset1 sys info 0x11100000 "Starting MP3 conversion script from "$(cd -P -- "$(dirname -- "$0")" && pwd -P)"/convert_mp3.sh"

IFS="`printf '\n\t'`"     # Remove 'space', so filenames with spaces work well.

FLAC_MAP="/volume1/music" # Folder with original FLAC-files
MP3S_MAP="/volume1/MP3s"  # Folder to store the converted MP3-files

# Notification mail variables
MAIL_FROM="mail@provider.com"
MAIL_TO="mail@provider.com"
MAIL_SUBJECT="Synology NAS: MP3 conversie is voltooid"
MAIL_BODY="Beste gebruiker,\n\nDe conversie van FLAC-bestanden naar MP3-bestanden is voltooid."
MAIL_CREATE_COUNTER="Totaal aantal geconverteerde of gekopieerde bestanden: "
MAIL_DELETE_COUNTER="Totaal aantal verwijderde bestanden: "
MAIL_STARTTIME="Starttijd: "
MAIL_TIMER="Duur: "
MAIL_REPORT="Bekijk de details in het conversie-rapport: "
MAIL_SIGNATURE="Met vriendelijke groeten,\nSynology DiskStation"

TIME_STAMP_START=`date`																					# Time stamp to store starting time
START_TIME=`date +%s`																				# Start time to calculate total processing time
REPORT_FILE=$(cd -P -- "$(dirname -- "$0")" && pwd -P)"/convert_mp3_"$(date +%Y-%m-%d)."txt"		# Define report filename

ECHO_CREATE_OUT="The following files were created:"
CREATE_COUNTER=0
ECHO_DELETE_OUT="The following files were deleted as the original file does no longer exist:"
DELETE_COUNTER=0

cd $FLAC_MAP
for a in `find . -name '*.flac' -print -o -name '*.mp3' -print -o -name 'folder.jpg' -print | sort`; do
	if [ -e "$a" ] ; then																			# Check if string from find is a file (should be the case)
		if [[ ${a} != *"#recycle"* ]]; then														 	# Skip files in the recycle bin, probably not deleted for nothing ;-)
			if [[ ${a} != *"@eaDir"* ]]; then														# Ignore @eaDir, this are folders with thumbnails & metadata.
				if [ ${a: -5} == ".flac" ]; then
					OUTF=${a%.flac}.mp3 															# Generate name of MP3-file
					OUTF="${OUTF:2}"																# Remove trailing ./ from the path
					
					if [[ ! -f "$MP3S_MAP/$OUTF" ]]; then											# Check if MP3-file does not already exists (if so, no conversion needed)
						path=$( echo ${OUTF%/*} )
						file=$( echo ${OUTF##/*/} )
		
						if [[ ! -e $MP3S_MAP/$path ]]; then
		    				mkdir -p $MP3S_MAP/$path												# Create folder if it does not yet exist in MP3-folder.
						fi
						echo "Converting ${a:2}"													# Show which FLAC-file is being converted to MP3
						ffmpeg -loglevel warning -i $a -acodec libmp3lame -q:a 1 "$MP3S_MAP/$file"	# Convert to MP3-file with quality Q:A 1 setting
						ECHO_CREATE_OUT+=$'\n'"- $MP3S_MAP/$file (converted FLAC-file)"				# Add MP3-filename to logging
						CREATE_COUNTER=$((CREATE_COUNTER+1))
					fi
				elif [ ${a: -4} == ".mp3" ] ; then
					if [[ ! -f "$MP3S_MAP/${a:2}" ]]; then											# Check if MP3-file does not already exists (if so, no conversion needed)
						path=$( echo ${a%/*} )
						if [[ ! -e $MP3S_MAP/$path ]]; then
		    				mkdir -p $MP3S_MAP/$path												# Create folder if it does not yet exist in MP3-folder.
						fi
						echo "Copying ${a:2}"
						cp $FLAC_MAP/${a:2} $MP3S_MAP/${a:2}										# Copy MP3-file, no need to convert if already MP3
						ECHO_CREATE_OUT+=$'\n'"- $MP3S_MAP/${a:2} (copied MP3-file)"
						CREATE_COUNTER=$((CREATE_COUNTER+1))
 					fi
				elif [ ${a: -10} == "folder.jpg" ] ; then
					if [[ ! -f "$MP3S_MAP/${a:2}" ]]; then											# Check if folder.jpg does not already exists (if so, making copy not needed)
						path=$( echo ${a%/*} )
						if [[ ! -e $MP3S_MAP/$path ]]; then
		    				mkdir -p $MP3S_MAP/$path												# Create folder if it does not yet exist in MP3-folder.
						fi
						echo "Copying ${a:2}"
						cp $FLAC_MAP/${a:2} $MP3S_MAP/${a:2}										# Copy folder.jpg.
						ECHO_CREATE_OUT+=$'\n'"- $MP3S_MAP/${a:2} (copied album art)"
						CREATE_COUNTER=$((CREATE_COUNTER+1))
 					fi
				fi
			fi
		fi
	fi
done

cd $MP3S_MAP
for a in `find . -name '*.mp3' -print -o -name 'folder.jpg' -print | sort`; do
	if [ -e "$a" ] ; then																			# Check if string from find is a file (should be the case)
		if [[ ${a} != *"#recycle"* ]]; then														 	# Skip files in the recycle bin, probably not deleted for nothing ;-)
			if [[ ${a} != *"@eaDir"* ]]; then														# Ignore @eaDir, this are folders with thumbnails & metadata.
				if [ ${a: -4} == ".mp3" ] ; then
					OUTF=${a%.mp3}.flac 															# Generate the name the original FLAC-file should have
					OUTF="${OUTF:2}"																# Remove trailing ./ from the path

					if [[ ! -f "$FLAC_MAP/$OUTF" ]]; then											# If the original FLAC file does not exist
						if [[ ! -f "$FLAC_MAP/$a" ]]; then											# and also original MP3 version of the file does not exist
							echo "Deleting $MP3S_MAP/${a:2}"
							rm -f $MP3S_MAP/${a:2}
							ECHO_DELETE_OUT+=$'\n'"- $MP3S_MAP/${a:2}"
							DELETE_COUNTER=$((DELETE_COUNTER+1))
						fi
					fi
				elif [ ${a: -10} == "folder.jpg" ] ; then
					if [[ ! -f "$FLAC_MAP/$a" ]]; then												# If the original folder.jpg file does not exist
						echo "Deleting $MP3S_MAP/${a:2}"
						rm -f $MP3S_MAP/${a:2}
						ECHO_DELETE_OUT+=$'\n'"- $MP3S_MAP/${a:2}"
						DELETE_COUNTER=$((DELETE_COUNTER+1))
					fi
				fi
			fi
		fi
	fi
done

find . -type d -empty -delete																	# Delete empty folders

TIME_STAMP_END=`date`	
END_TIME=`date +%s`																				# End time to calculate total processing time
PROCESS_SECS=$(( $END_TIME - $START_TIME ))														# Calculate total processing time in seconds
PROCESS_TIME="`printf '%02dh:%02dm:%02ds\n' $(($PROCESS_SECS/3600)) $(($PROCESS_SECS%3600/60)) $(($PROCESS_SECS%60)) `"

if test "$ECHO_CREATE_OUT" != "The following files were created:" || test "$ECHO_DELETE_OUT" != "The following files were deleted as the original file does no longer exist:"; then
	if test "$ECHO_CREATE_OUT" != "The following files were created:"; then
		echo $"$ECHO_CREATE_OUT" >> $REPORT_FILE
	fi
	
	if test "$ECHO_DELETE_OUT" != "The following files were deleted as the original file does no longer exist:"; then
		if test "$ECHO_CREATE_OUT" != "The following files were created:"; then
			echo $'\n' >> $REPORT_FILE
		fi
		echo $"$ECHO_DELETE_OUT" >> $REPORT_FILE
	fi

	echo $"Converted or copied: "$CREATE_COUNTER" file(s)" >> $REPORT_FILE
	echo $"Deleted: "$DELETE_COUNTER" file(s)" >> $REPORT_FILE
	echo $"Start time: "$(date +"%Y-%m-%d %H:%M" -d "$TIME_STAMP_START") >> $REPORT_FILE
	echo $"END time: "$(date +"%Y-%m-%d %H:%M" -d "$TIME_STAMP_END") >> $REPORT_FILE
	echo $"Total processing time: "$PROCESS_TIME >> $REPORT_FILE
	
	/usr/bin/php -r 'mail("'$MAIL_TO'", "'$MAIL_SUBJECT'", "'$MAIL_BODY'\n\n'$MAIL_CREATE_COUNTER$CREATE_COUNTER'\n'$MAIL_DELETE_COUNTER$DELETE_COUNTER'\n'$MAIL_STARTTIME$(date +"%Y-%m-%d %H:%M" -d "$TIME_STAMP_START")'\n'$MAIL_TIMER$PROCESS_TIME'\n\n'$MAIL_REPORT$REPORT_FILE'\n\n'$MAIL_SIGNATURE'", "From: '$MAIL_FROM'");';
	/usr/syno/bin/synologset1 sys info 0x11100000 "Finished MP3 conversion script. Number of converted files: "$CREATE_COUNTER". Number of deleted files: "$DELETE_COUNTER". Total processing time: "$PROCESS_TIME". See all details in the conversion-report: "$REPORT_FILE;
else
	echo $"No files needed to be converted, copied or deleted.";
	/usr/syno/bin/synologset1 sys info 0x11100000 "Finished MP3 conversion script. No files needed to be converted, copied or deleted. Total processing time: "$PROCESS_TIME;
fi

3 reacties

  1. Hoi Jos,
    Ik was al een hele poos op zoek naar een oplossing die mijn FLAC’s automatisch kan converteren naar MP3 voor in de auto, geweldig!
    Ik krijg alleen jouw script niet goed werkend. Heb FFMPEG geinstalleerd, het script opgeslagen als convert.sh en vervolgens een scheduled task aangemaakt voor een user-defined script. Uitgevoerd onder root en als run command “bash /volume1/data/scripts/convert.sh”
    Maar bij start krijg ik direct als status ‘interrupted’.
    Hoe heb jij jouw script draaien op je Synology?
    Alvast bedankt!

    • Hi, nog even gekeken, maar ik heb eigenlijk niet zo heel veel bijzonders kunnen constateren. Ik neem aan dat je de twee mappen hebt aangepast naar jouw eigen situatie? Dus dit stukje;

      FLAC_MAP=”/volume1/music” # Folder with original FLAC-files
      MP3S_MAP=”/volume1/MP3s” # Folder to store the converted MP3-files

      Verder zou je in deze regel;

      ffmpeg -loglevel warning -i $a -acodec libmp3lame -q:a 1 “$MP3S_MAP/$file” # Convert to MP3-file with quality Q:A 1 setting

      … het loglevel kunnen aanpassen naar debug (dus “warning” vervangen voor “debug”). Dat geeft hopenlijk meer details m.b.t. wat er fout gaat.

      Op welke type NAS probeer je dit script overigens te draaien?

Geef een reactie

Je e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *

Deze site gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.