Friday, October 2, 2020

How to trim audio (MP3) files

Summary: PowerShell script to trim beginning and end of the audio (MP3, etc) files.
The following PowerShell script will remove the specified number of seconds from the beginning and/or end of every audio file with the given extension (.mp3 in this case) under the specified folder and all subfolders unerneath (requires FFmpeg binaries):
# Input folder holding audio files.
$inputDir = "Z:\Lectures"

# Seconds to trim from beginning of file.
$trimStart = 0.0

# Seconds to trim from the end of file.
$trimEnd = 9.0

# Path to the directory holding FFMPEG tools.
$ffmpegDir = "c:\ffmpeg\bin"

# Extension of the audio files.
$ext = ".mp3"

# Extension for temporary files.
$tmpExt = ".TMP$ext"

# Paths to FFMPEG tools.
$ffmpeg  = Join-Path $ffmpegDir "ffmpeg.exe"
$ffprobe = Join-Path $ffmpegDir "ffprobe.exe"

# Process all audio files in the directory and subdirectories.
Get-ChildItem -LiteralPath $inputDir -Filter "*$ext" -Recurse -File | ForEach-Object {
    # Original file path.
    $oldFile = $_.FullName

    # Original file name.
    $oldName = $_.Name

    # Temp file path will be in the same folder named after the original file.
    $tmpFile = "$oldFile$tmpExt"

    # Get the length of the audio track (it's a sting holding a floating number with possible new line).
    $duration = (& $ffprobe -v 0 -show_entries format=duration -of compact=p=0:nk=1 $oldFile) | Out-String

    $duration = $duration.Trim()

    # Set new length of the audio by removing the trimmed parts.
    $duration -= ($trimEnd + $trimStart)

    # Trim the file.
    & $ffmpeg -ss $trimStart -t $duration -i $oldFile -acodec copy $tmpFile

    # Delete the original file.
    Remove-Item -LiteralPath $oldFile -Force

    # Rename the temp file to the original.
    Rename-Item -LiteralPath $tmpFile $oldName -Force