Blog-Archiv

Dienstag, 17. September 2024

Add or Remove Audio to or from Video with ffmpeg

Here are lossless UNIX shell-scripts to create a new video from a given video, either by adding a given audio track, or by removing the existing audio track. The scripts ensure that the source-video is not overwritten by the newly created one.

Please mind that expressions like ${sourceFile%.*} and ${sourceFile#*.} may be not supported by some UNIX shell implementations!

Add Audio to Video

fileMarker=audio

[ -z "$1" -o ! -f "$1" -o -z "$2" -o ! -f "$2" ] && {
	echo "SYNTAX: $0 videoFile audioFile" >&2
	echo "	Adds given audio track to given video, creating an xxx_$fileMarker.mp4 file." >&2
	exit 1
}

sourceVideo=$1
sourceDir=`dirname \$sourceVideo`
sourceFile=`basename \$sourceVideo`
filename=${sourceFile%.*}	# filename without extension
extension=${sourceFile#*.}	# extension without filename
targetVideo=$sourceDir/${filename}_$fileMarker.$extension

audio=$2

ffmpeg -v error -y -i $sourceVideo -i $audio -map 0:v -map 1:a -c:v copy -c:a copy $targetVideo

echo "Created $targetVideo"

The -c:v copy option guarantees losslessness.


Remove Audio from Video

fileMarker=noaudio

[ -z "$1" -o ! -f "$1" ] && {
	echo "SYNTAX: $0 videoFile" >&2
	echo "	Removes audio track(s) from given video, creating an xxx_$fileMarker.mp4 file." >&2
	exit 1
}

sourceVideo=$1
sourceDir=`dirname \$sourceVideo`
sourceFile=`basename \$sourceVideo`
filename=${sourceFile%.*}	# filename without extension
extension=${sourceFile#*.}	# extension without filename
targetVideo=$sourceDir/${filename}_$fileMarker.$extension

ffmpeg -v error -y -i $sourceVideo -an -c:v copy $targetVideo

echo "Created $targetVideo"

Important are both -an and -c:v copy options. The -an excludes any audio track from copying, the -c:v copy avoids the ffmpeg default re-encoding of the video (makes the copy lossless). If you pass e.g. a file named myVideo.mp4 to this script, it will generate myVideo_noaudio.mp4 as result, residing in the directory where the original video is.




Keine Kommentare: