beaTunes News

Monday, October 7, 2013

Exporting Playlists to Spreadsheets

beaTunes2 logoThe other day someone asked on http://help.beatunes.com/ how he could export a playlist to a spreadsheet. Frankly, I loved the question, because it gave me a perfect opportunity to show off the beaTunes plugin API. Specifically, it gave me a chance to demonstrate how to write a PlayListExporter beaTlet.

The overall idea is very simple: All spreadsheet applications can import CSV. CSV stands for comma separated values and each line in such a file is just that. So all we have to do, is write some header with the column names, and then write the desired song attributes for each song. The only slightly complicated thing here, is the fact that we need to escape quotes and have to take care of possible null values.

The result is a little beaTlet (basically a script using the plugin API) written in Groovy that can be installed by placing it into the beaTunes plugin directory as explained here and here. Make sure to call the file the same as its class name: CSVPlayListExporter.groovy

To use it, restart beaTunes, right-click on a playlist, and choose Export PlaylistCSV. Then type in the file name and make sure to use the file extension .csv.

import java.io.File
import com.tagtraum.core.ProgressListener
import com.tagtraum.beatunes.library.PlayListExporter 
import com.tagtraum.beatunes.library.PlayList

class CSVPlayListExporter implements PlayListExporter {

    // Lowercase file extension (without the '.').
    def String getFileExtension() {
        "csv"
    }

    // Very short description for this exporter.
    def String getDescription() {
        "CSV"
    }

    // Lets you provide an id for this exporter.
    // The id may be used for referring to an instance of this exporter
    // in persistent configuration files.
    def String getId() {
        "groovy.csvplaylistexporter"
    }

    // Exports the given playlist to the given file.
    //
    // file to write to
    // playlist to export
    // progressListener that lets you report... well, progress
    def void export(File file, PlayList playList, ProgressListener progressListener) {
        file.withWriter { f ->
            // write CSV header for column names
            f.writeLine("Name,Album,Artist,Composer,Key,BPM")
            // write a comma separated line for each song
            playList.getSongs().each() { song ->
                f.writeLine("${esc(song.getName())},"
                + "${esc(song.getAlbum())},"
                + "${esc(song.getArtist())},"
                + "${esc(song.getComposer())},"
                + "${esc(song.getKey())},"
                + "${String.format(Locale.US, "%s", song.getBeatsPerMinute())}")
            }
        }
    }
    
    def String esc(Object s) {
        if (s == null) return ""
        "\"" + s.toString().replace("\"", "\"\"") + "\""
    }
}

Download

Labels: ,

0 Comments:

Post a Comment

<< Home