Generate M3U Playlist with PowerShell

Woman with headphones in a train station.

MP3s are everywhere, and back in 2014 I finally had a phone with enough storage for a decent number of them. I use MediaMonkey to add high-resolution album covers and to rename the files in a predictable format: Artist - Album - # - Title. The only thing I was missing was a simple way of creating an M3U playlist: PowerShell to the rescue!

The GenerateM3U function

Let's create a function that takes a directory and generates an M3U playlist file:

function GenerateM3U {
    param(
        [System.IO.DirectoryInfo] $directory,
        [string] $playlistFileName = "",
        [string] $pattern = "*.mp3"
    )

    # Make sure we add .m3u as an extension
    if ( [string]::IsNullOrWhiteSpace($playlistFileName) ) {
        $playlistFileName = $directory.Name + ".m3u"
    }
    elseif ( $playlistFileName -ne [System.IO.Path]::GetFileName($playlistFileName) ) {
        throw "playlistFileName must be a file name without a directory."
    }
    elseif ( [System.IO.Path]::GetExtension($playlistFileName) -ine ".m3u" ) {
        $playlistFileName = "$playlistFileName.m3u"
    }

    # Store the playlist next to the files so relative paths work
    $playlistFileName = Join-Path -Path $directory -ChildPath $playlistFileName

    # Remove old file
    if ( Test-Path $playlistFileName -PathType Leaf ) {
        Remove-Item $playlistFileName
    }

    # Only read MP3 files
    if ( [string]::IsNullOrEmpty([System.IO.Path]::GetExtension($pattern)) ) {
        $pattern = "$pattern*.mp3"
    }
    elseif ( [System.IO.Path]::GetExtension($pattern) -ine ".mp3" ) {
        throw "pattern must match MP3 files."
    }

    # Write M3U
    $directory.GetFiles($pattern) |
        ForEach-Object { $_.Name } | 
        Sort-Object |
        Out-File -Encoding UTF8 -FilePath $playlistFileName
}

Now we can call the function in a few different ways to create an M3U playlist:

# Generate based on a directory:
GenerateM3U "./Gavin James - For You"

# Generate named M3U:
GenerateM3U "./Gavin James - For You" "kees.m3u"

# Generate named M3U of certain MP3 files:
GenerateM3U "./Gavin James - For You" "kees2.m3u" "Gavin*.mp3"

Caveat: Out-File encoding

This encoding caveat applies to Windows PowerShell 5.1. PowerShell 6 and later defaults to UTF-8 without a byte order mark (BOM), and -Encoding utf8 also writes UTF-8 without a BOM. See Microsoft's about_Character_Encoding documentation for version-specific behavior.

While working on this code I initially omitted the encoding. This led to an MRL exception in VLC:

VLC player showing an MRL exception for an M3U playlist with the wrong encoding.
VLC initially did not like the file we generated.

When inspecting the file in an online HEX editor, we see some weird characters:

Screenshot of the HEX editor showing the M3U file that was written without specifying the encoding.
The HEX editor shows which characters are actually used in the M3U file.

This is a UTF-16 little-endian byte order mark, which VLC did not interpret correctly. In Windows PowerShell 5.1, adding -Encoding utf8 to the Out-File statement writes UTF-8 with a BOM. This adds EF BB BF to the beginning of the file, which is something VLC understands.

In the comments, it was pointed out that -Encoding Default works better for Windows Media Player when using Windows PowerShell 5.1. It also works with VLC, but characters that are not available in the active Windows code page can become corrupted.

Final thoughts

Because of the default PowerShell Out-File encoding, generating an M3U playlist is less straightforward than I thought. A HEX editor is a great way of debugging these encoding problems.

Changelog

  • Corrected the encoding explanation and playlist path handling. Improved wording.
  • Added comment about -Encoding default and Windows Media Player.
  • Images are now zoomable.
  • Rewrote the article. Created a simple function instead of a script. Added an analysis of the encoding problem VLC was facing.
  • Initial article
  1. Barry Gallagher says:

    Hi thats great ;Just what I was looking for!!!
    one thing that would really help me and I would be so grateful if you could advise:
    Is there a way it could only add the files if they were created after a certain date/time.
    Eg if I passed the function a TimeStamp “2020-08-05 15:50:00” could I make the function add all files to the playlist after that time, including sub directories?
    Thank you for your help so far!
    Baz

  2. Willy says:

    Hi Kees,

    On my Windows 10 Pro system, if I used
    Out-File -Encoding default
    it would save in the .m3u file in a UTF-8 format that was readable by Windows Media Player. When I used
    Out-File -Encoding utf8
    it would save in the .m3u file in a UTF-8 w/ BOM format that was unreadable in Windows Media Player.

    Now if I could only figure out how to have PowerShell read the track # from the MP3tag and then create the playlist in the proper order.

    Willy

    1. Kees C. Bakker says:

      Thanks Willy, I added the comment (a bit late). If you’re still looking into reading MP3 tags, I’ve used https://www.nuget.org/packages/TagLibSharp in a C# project and it works really well. You might be able to use it in PowerShell as well.

expand_less brightness_auto