Converting audio files en masse

We recently got a new (used) family van that has a 40 gig hard drive in the dash to store MP3 files. Problem is, a lot of my audio files were stored as M4A, which the van doesn’t have a codex for. On top of that, my wife just got a karaoke machine for the kids that also only plays MP3 format. So, I wrote a script that uses FFMPEG to do the file conversion and then uses TagLib to copy over the ID3 tag info (because if a file isn’t ID3 tagged, I don’t want it).

[CmdletBinding()]
Param (
    [Parameter(Mandatory=$True)]
    [string]$rootPath
)

$scriptRoot = "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)"
[system.reflection.assembly]::loadfile("$scriptRoot\taglib-sharp.dll")

function ConvertToMp3 ([string]$oldFile) {
    # FFMPEG Documentation
    # https://www.ffmpeg.org/ffmpeg.html
    [string] $ffmpeg = '$scriptRoot\ffmpeg.exe'
    $newFile = $oldFile.Replace(".m4a", ".mp3")
    & $ffmpeg -i "$oldFile" "$newFile" -y
    DuplicateId3Tags $oldFile $newFile
}

function DuplicateId3Tags {
    #TagLib API Documentation - http://taglib.github.io/api/index.html
    Param (
        [string]$oldTag,
        [string]$newTag
    )

    $sourceM4a = [TagLib.File]::Create($oldTag)
    $targetMp3 = [TagLib.File]::Create($newTag)
    #http://taglib.github.io/api/classTagLib_1_1Tag.html#pub-static-methods
    [TagLib.Tag]::Duplicate($sourceM4a.Tag, $targetMp3.Tag, $true)
    $targetMp3.Save()
}

function ConvertAllToMp3 ([string] $sourcePath) {
    $files = Get-ChildItem "$sourcePath\*" -recurse -include *.m4a
    ForEach ($file in $files) {
        ConvertToMp3 $file.FullName
        # Uncomment to remove old file
        # Remove-Item -Path $file.FullName -Force 
    }
}

ConvertAllToMp3 $rootPath
Advertisements
This entry was posted in Programming and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s