Search code examples
powershellmetadatataglib-sharp

Update a song metadata with taglib-sharp and Powershell


I am trying to update a song metadata with taglib-sharp and powershell. It works fine for most of the files but there are errors on some wma files (I can play these files though).

# Load the tag-lib assembly
[Reflection.Assembly]::LoadFrom( (Resolve-Path ("D:\zic\lib\taglib-sharp.dll")))

# Load up the song file and its metadata
$path_file="‪D:\zic\misc\Artist_Title.wma"
$song = [TagLib.File]::Create((resolve-path $path_file))
$file_name = [System.IO.Path]::GetFileNameWithoutExtension($path_file) 
$file_name_array=$file_name.Split("_")
$artist=$file_name_array[0]
$title=$file_name_array[1]

#set the artist and title (metadata)
$song.Tag.Artists = $artist 
$song.Tag.AlbumArtists = $artist 
$song.Tag.Title = $title

# Save the metadata 
$song.Save() 

The error appears when the file is saved: enter image description here

Is it a powershell problem? A taglib-sharp problem? I am using taglib_sharp version 2.0.50727 and powershell version 5.1.16299.248.


EDIT

With a try catch to show the error:

# Save the metadata
try
{
    $song.Save() 
}
catch [Exception]
{
    Write-Host $_.Exception|format-list -force
}

The console displays:

enter image description here


EDIT 2

If I edit the tags manually (right click on the file -> properties) or rename the file, the program runs without problem and the tags are updated. Weird!


Solution

  • As @tukan suggested, the length of some tags was the problem.

    Let's display all the tags of a song:

    $song = [TagLib.File]::Create((resolve-path $path_file))
    foreach ($tag in $song.Tag)
    {
        Write-Host "tag:" $tag
    }
    

    The output:

    tag:
    tag: {D1607DBC-E323-4BE2-86A1-48A42A28441E}
    tag: 10.00.00.3802
    tag: 0.0.0.0000
    tag: 0
    tag: 2007
    tag: 128317523430000000
    tag: AMGa_id=R  1411185;AMGp_id=VA;AMGt_id=T 14593744
    tag: Éri Tabuhci
    tag: Universal
    tag: World
    tag: Les 100 Plus Grands Tubes Disc 3
    tag: Unknown Artist
    tag: 14+96+34B7+ADE8+E42D+11DF5+15230+196F2+1C2D1+1FC01+257E9+29612+2D100+30FB0+34ECE+3923F+3D39B+40CF6+454FF+49162+4D5D0+521B0
    tag: AMG
    tag: World
    tag: 5
    

    The fourth tag from the end is too long and is the cause of the problem. The solution is to load the file, remove all the existing tags, save it, load it again and then set the tags you want. For example:

    $song = [TagLib.File]::Create((resolve-path $path_file))
    $song.RemoveTags($song.TagTypes)
    $song.Save()
    
    $song = [TagLib.File]::Create((resolve-path $path_file))
    $song.Tag.Artists = "blabla"
    ...
    

    Hope this helps!