Friday, December 5, 2014

Reading and Writing MusicXml Files with Java

Download JFugue with Music Xml Support from JFugue Downloads. Click on jfugue-4.0.3-with-musicxml.jar. Change your pom.xml file and run "mvn install" as described in Adding an external Jar to a Maven Project (JFugue). Then add the following code (and include the code found in Reading and Writing Files in Java):

package com.mycompany.app.util;

import java.io.File;
import org.jfugue.MusicStringParser;
import org.jfugue.MusicStringRenderer;
import org.jfugue.MusicXmlParser;
import org.jfugue.MusicXmlRenderer;
import org.jfugue.Pattern;
import org.jfugue.Player;

public class MusicXMLFileHelper {
    
    public static void main(String[] args) { 
        try {
            System.out.println("START");
            String outputFile = "/Users/Scott/workspace/myrepo/my-app/output/mxmlfhout.xml";
            Pattern pattern = new Pattern("KEmaj V0 E4i+B4i B3i E4i+B4i B3i E4i+B4i B3i E4i+B4i B3i V1 E1h E1i F#1i G#1i B1i");
        
            MusicXMLFileHelper fileHelper = new MusicXMLFileHelper(); 
            fileHelper.write(new File(outputFile), pattern);
            
            Player player = new Player();
            player.play(pattern);
            System.out.println("FINISH");
        } catch (Exception ex) {
            
        }
    }
    
    public void write(File outputFile, Pattern musicPattern) throws Exception {
        MusicXmlRenderer renderer = new MusicXmlRenderer();
        
        MusicStringParser parser = new MusicStringParser();
        parser.addParserListener(renderer);
        parser.parse(musicPattern);
        
        FileHelper fileHelper = new FileHelper();
        fileHelper.write(outputFile, renderer.getMusicXMLString());
    }
    
    public Pattern read(File inputFile) throws Exception{
        MusicStringRenderer renderer = new MusicStringRenderer();

        MusicXmlParser parser = new MusicXmlParser();
            
        parser.addParserListener(renderer);
        parser.parse(inputFile);
        
        return renderer.getPattern();
    }
}


This post was reposted from http://scottizu.wordpress.com/2013/08/19/reading-and-writing-musicxml-files-with-java/, originally written on August 19, 2013.

No comments:

Post a Comment