Similar to my previous post in which I was using PowerShell and ImageMagick, these evening I needed to take a folder of large mp3 files and trim them (extract only the first minute of audio) and save the audio into another folder.
For my audio transformation I used FFMPEG – which rules. All I needed to do is write the Script that called. The code is below and is been written to follow a general pattern that these kinds of batch operations take. Thus, you should be able to modify it easily to suit you needs.
$ffmpeg_exe = "D:\ffmpeg\bin\ffmpeg.exe"
Function Folder_to_Folder_MP3_Trim
{
Param(
[Parameter(Mandatory=$true)]
[String] $FromFolder,
[Parameter(Mandatory=$true)]
[String] $ToFolder,
[Parameter(Mandatory=$false)]
[String] $FromInclude
)
Process
{
$count=0
$fromitems = Get-ChildItem $FromFolder -include $FromInclude -recurse
foreach ($fromitem in $fromitems)
{
$basename = $fromitem.Name
Write-Verbose "Item [$count]: $basename"
if ($fromitem.PsIsContainer -eq $true)
{
Write-Verbose "`TYPE: Directory"
}
else
{
Write-Verbose "`tTYPE: File"
}
$from_fullname = $fromitem.FullName
Write-Verbose "`tFROM: $from_fullname"
$to_fullname = Join-Path $ToFolder $fromitem.FullName.Substring( $FromFolder.Length )
Write-Verbose "`t TO: $to_fullname"
if ($fromitem.PsIsContainer -eq $true)
{
Write-Verbose "`TYPE: Directory"
}
else
{
Write-Verbose "`tTYPE: File"
}
$to_directory = Split-Path $to_fullname -Parent
if ( !(Test-Path $to_directory))
{
Write-Verbose "`tDestination directory does not exist"
New-Item $to_directory -ItemType Directory
}
if ( Test-Path $to_fullname)
{
Write-Verbose "`tDestination item exists"
if ($fromitem.PsIsContainer -eq $true)
{
}
else
{
Write-Verbose "`tDeleting existing destination item"
Remove-Item $to_fullname
}
}
$count++
$cmdline = "$ffmpeg_exe -t 60 -i `"$from_fullname`" -acodec copy `"$to_fullname`" "
Write-Verbose "`t CMD: $cmdline"
invoke-expression -command $cmdline
}
Write-Verbose "Handled $count items"
}
}
Folder_to_Folder_MP3_Trim -FromFolder "D:\InputAudio" -ToFolder "D:\OutputAudio" -Verbose