PHPackages                             planetbiru/musicxml - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PDF &amp; Document Generation](/categories/documents)
4. /
5. planetbiru/musicxml

ActiveLibrary[PDF &amp; Document Generation](/categories/documents)

planetbiru/musicxml
===================

A PHP library to convert MIDI files to MusicXML and DAWPRoject, and render them as PDF or SVG.

v1.3.0(1mo ago)440↓75%MITPHPPHP &gt;=5.6

Since Jul 14Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/Planetbiru/MusicXML)[ Packagist](https://packagist.org/packages/planetbiru/musicxml)[ Docs](https://www.planetbiru.com)[ RSS](/packages/planetbiru-musicxml/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (8)Dependencies (2)Versions (23)Used By (0)

Planetbiru MusicXML Converter
=============================

[](#planetbiru-musicxml-converter)

[![Latest Stable Version](https://camo.githubusercontent.com/dd96cf3e9392744abf91c5384baeeb358523d44f9d35ff136493add178ff721b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f706c616e6574626972752f6d75736963786d6c2e737667)](https://packagist.org/packages/planetbiru/musicxml)[![License](https://camo.githubusercontent.com/37551ed01499378d9417a4fbe20e082e69584f6aa167f2f7b6165967b9303b7a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f706c616e6574626972752f6d75736963786d6c2e737667)](https://opensource.org/licenses/MIT)

This is more than just a MIDI-to-MusicXML converter; it's a comprehensive PHP toolkit for developers working with musical data. It provides robust tools to parse, convert, and render music from various formats, including MIDI, MusicXML, and DAWProject. The library excels at generating beautiful, interactive sheet music as PDFs or SVGs, all in pure PHP with minimal dependencies. This library is actively used in production and powers the online sheet music generator at .

Key Features
------------

[](#key-features)

- **MIDI to MusicXML:** Core functionality to parse MIDI data and convert it into a standard MusicXML structure.
- **MusicXML to MIDI:** Convert MusicXML object models back into binary MIDI files, enabling a full roundtrip conversion process.
    - This roundtrip capability is powerful for building interactive **MusicXML players**. The workflow is as follows:
        1. The MusicXML is converted to a MIDI file for audio playback.
        2. The same MusicXML is converted to an SVG for visual rendering, allowing for synchronized highlighting of notes and lyrics as the audio plays.
- **MIDI to DAWProject Conversion:** Added functionality to convert standard MIDI files into the `.dawproject` format, compatible with DAWs like Bitwig Studio.
- **DAWProject to MIDI Conversion:** Implemented the reverse conversion, allowing `.dawproject` files to be converted back into standard MIDI files.
- **Roundtrip Conversion Capability:** The new features enable a full roundtrip conversion (`MIDI` -&gt; `.dawproject` -&gt; `MIDI`), preserving track structure and instrument information.
- **SVG Rendering:** Create scalable SVG vector graphics of your sheet music from MusicXML data, perfect for web display.
    - **Interactive:** The generated SVG includes `data-*` attributes for easy synchronization with an audio player, enabling features like note highlighting and a moving playhead.
    - **Page-by-Page Preview:** In addition to a single, continuous scrolling view, the SVG can also be rendered in a multi-page layout, similar to a PDF. This is useful for previewing how the score will look when printed. This behavior is controlled by a parameter in the conversion function.
    - **Mobile-Optimized Layout:** A `$mobile` flag renders the score with one measure per line on a narrower canvas, perfect for vertical scrolling on mobile devices.
- **PDF Rendering:** Generate high-quality PDF sheet music from MusicXML data using a built-in FPDF-based rendering engine. No external binaries required.
- **Track &amp; Channel Filtering:** Easily select a specific track or channel from a MIDI file to render.
- **Automatic Part Detection:** Intelligently detects the most suitable part to render (e.g., the main melody with lyrics).
- **Rich Notation Support:** Handles notes, rests, chords, ties, time signatures, key signatures, clefs, and tempo markings.
- **Advanced Beaming:** Automatically groups notes (eighths, sixteenths, etc.) with beams according to standard music notation rules, respecting beat boundaries and complex rhythms. Beams are slanted to follow the melodic contour. This feature is optional.
- **Lyric Support:** Automatically detects and renders lyrics embedded in MIDI files.
- **Percussion &amp; Drums:** Special handling for drum tracks (Channel 10) with appropriate notation.
- **Batch Processing:** Includes examples for processing all tracks of a MIDI file into a single ZIP archive of PDFs.

Conversion Workflows
--------------------

[](#conversion-workflows)

The library supports the following conversion workflows:

[![Conversion Compatibility](conversion-compatibility.svg)](conversion-compatibility.svg)

- **DAWProject → MIDI:** Parse DAWProject files and reconstruct MIDI tracks/events, including tempo, notes, and program changes.
- **MIDI → DAWProject:** Convert MIDI data into DAWProject format (ZIP with project.xml and metadata.xml), preserving tempo, tracks, notes, and instrument mapping for DAW interoperability.
- **MIDI → MusicXML:** Parse MIDI data and convert it into a standard MusicXML structure.
- **MusicXML → MIDI:** Convert MusicXML object models back into binary MIDI files.
- **MusicXML → PDF:** Render MusicXML data into high-quality, printable PDF sheet music.
- **MusicXML → SVG:** Render MusicXML data into scalable SVG, perfect for interactive web display.

Format Comparison and Data Loss
-------------------------------

[](#format-comparison-and-data-loss)

When converting between MIDI, MusicXML, and DAWProject, it's important to understand that each format was designed for a different purpose. As a result, some information can be lost in translation.

### Feature Comparison Matrix

[](#feature-comparison-matrix)

FeatureMIDI (.mid)MusicXML (.xml, .mxl)DAWProject (.dawproject)**Primary Purpose**Performance DataDigital Sheet MusicDAW Session Interchange**Note Data**Yes (Pitch, Velocity, Timing)Yes (with rich notation)Yes (within clips)**Sheet Music Notation**No (Inferred by converter)**Yes (Primary feature)**No (Inferred by converter)**Lyrics**Yes (as timed meta-events)Yes (syllable-based, well-structured)No (Not supported in the spec)**Continuous Controllers**Yes (Pitch Bend, Modulation, etc.)Limited (often simplified or lost)Yes (as automation curves)**Track Structure**YesYes (as "Parts")Yes (Audio, Instrument, etc.)**Audio Clips**NoNoYes (References external files)**Plugin/VST State**NoNoYes (Can store plugin info)### Conversion Data Loss

[](#conversion-data-loss)

Understanding what is lost during conversion is key to choosing the right workflow for your needs.

#### **MIDI → MusicXML**

[](#midi--musicxml)

This is a "performance-to-notation" conversion. The goal is to create readable sheet music from raw performance data.

- **What is LOST:**
    - **Continuous Performance Data:** Nuanced pitch bends, modulation wheel curves, and other continuous controller (CC) data are generally lost or heavily simplified.
    - **Precise Timing:** Unquantized, "human" timing is snapped to a rhythmic grid (quantized). This can alter the feel of the original performance.
    - **Panning:** Pan (CC10) information is typically discarded.
    - **Complex Dynamics:** The interplay between note velocity, volume (CC7), and expression (CC11) is flattened into a single dynamic marking (e.g., *mf*, *p*).

#### **MusicXML → MIDI**

[](#musicxml--midi)

This is a "notation-to-performance" conversion. The goal is to create an audible representation of the sheet music.

- **What is LOST:**
    - **Visual Notation:** All visual-only information is lost. This includes slurs, specific beam groupings, page layout, and textual annotations that don't have a direct playback meaning.
    - **Semantic Meaning:** The distinction between enharmonically equivalent notes (e.g., F# vs. Gb) is lost. The MIDI file only knows the pitch, not its theoretical context.
    - **Note Velocity:** The final note velocity is an interpretation of the MusicXML dynamic markings, not a restoration of the original performance velocity.

#### **MIDI → DAWProject**

[](#midi--dawproject)

This conversion focuses on preserving core musical data like notes, tracks, and tempo for interoperability between DAWs.

- **What is LOST:**
    - **Lyrics:** The `.dawproject` format does not have a standard way to represent lyrics, so they are lost during this conversion.
    - **Other Meta-Events:** Some non-standard or less common MIDI meta-events may not be translated.

#### **DAWProject → MIDI**

[](#dawproject--midi)

This conversion extracts musical event data from a DAW session file.

- **What is LOST:**
    - **DAW-Specific Information:** All data related to audio clips, VST/plugin states, routing, and scene structure is lost. The conversion only extracts the MIDI-related information from instrument clips.

#### **Conclusion: The Best Format for the Job**

[](#conclusion-the-best-format-for-the-job)

- **Use MIDI** as the source when you have raw performance data from a keyboard or sequencer and want to generate sheet music or a DAW project from it.
- **Use MusicXML** when your primary goal is to create, edit, or share digital sheet music with accurate and detailed notation. It is the best format for exchanging scores between notation software (Sibelius, Finale, MuseScore).
- **Use DAWProject** for exchanging a project's structure—including MIDI clips, tempo, and track information—between compatible DAWs (like Bitwig Studio and Cubase). It is not a format for detailed notation.

Due to these differences, a round-trip conversion like `MIDI → MusicXML → MIDI` will **not** produce a file identical to the original. The resulting MIDI will be a quantized, simplified performance based on the generated sheet music, not a perfect copy of the original performance.

MusicXML 4.0 Compliance
-----------------------

[](#musicxml-40-compliance)

The object model in this library, primarily located within the `MusicXML\Model` namespace, is designed to accurately reflect the official MusicXML 4.0 specification. Each PHP class, such as `Accidental`, `Note`, `MeasurePartwise`, and others, corresponds directly to an element defined in the MusicXML standard.

This 1:1 mapping approach ensures that the generated XML output is well-structured, valid, and broadly compatible with various music notation software that supports MusicXML (such as Sibelius, Finale, MuseScore, etc.). When you work with the PHP objects in this library, you are essentially building a MusicXML document programmatically.

For a complete and detailed reference of all elements, their attributes, and expected values, please refer to the official element reference from W3C MusicXML 4.0. For instance, the `Accidental` class in this library corresponds to the `` element described in the documentation. You can find a complete list of all elements at:

- **MusicXML 4.0 Element Reference**

As a specific example, the `` element can be found in this documentation.

Installation
------------

[](#installation)

Install the library via Composer:

```
composer require planetbiru/musicxml
```

Usage
-----

[](#usage)

The `MusicConverter` class is the main entry point and the easiest way to use this library. Think of it as the primary "conversion engine" that does all the heavy lifting for you.

When you provide a MIDI file, `MusicConverter` automatically performs the following steps behind the scenes:

1. **Reads &amp; Analyzes MIDI:** It understands all the data from the MIDI file, such as notes, tempo, instruments, and lyrics.
2. **Converts to MusicXML:** It translates that MIDI data into the MusicXML format, which is the standard "language" for digital music notation.
3. **Renders to Visuals:** It draws the MusicXML structure into your desired visual format, either a print-ready PDF or an interactive SVG for the web.

You don't need to worry about the technical details of each step; you just need to call a single function.

### Constructor

[](#constructor)

`new MusicConverter($compressEmptyMeasures, $showTempoChanges, $useRestFilling, $lyricFontSize, $systemHeight, $drawBeam)`

Initializes the converter with optional rendering settings.

- `$compressEmptyMeasures` (bool): If `true`, consecutive empty measures will be collapsed into a single multi-measure rest. Default is `false`.
- `$showTempoChanges` (bool): If `true`, tempo change markings (e.g., "Tempo: = 120") will be displayed on the score. Default is `true`.
- `$useRestFilling` (bool): If `true`, uses an alternative algorithm for filling gaps with rests. This can affect how rests are displayed in measures with complex rhythms. Default is `false`.
- `$lyricFontSize` (float): The font size for lyrics, in points. Default is `6.0`.
- `$systemHeight` (int): The vertical height of a single staff system in millimeters, including space for lyrics. Default is `28`.
- `$drawBeam` (bool): If `true`, notes shorter than a quarter note will be grouped with beams instead of individual flags. Default is `false`.

### Core Conversion Methods

[](#core-conversion-methods)

Here are the main public methods available in the `MusicConverter` class:

#### `midiToMusicXML($midiData, $songTitle, $version, $format)`

[](#miditomusicxmlmididata-songtitle-version-format)

Converts MIDI data into a MusicXML string.

- `$midiData` (string): The binary content of a MIDI file.
- `$songTitle` (string): The title for the musical work. Defaults to "Untitled".
- `$version` (string): The MusicXML version to use. Defaults to "4.0".
- `$format` (string): The output format, either 'xml' (uncompressed) or 'mxl' (compressed). Defaults to "musicxml".

#### `midiToDAWProject($midiData)`

[](#miditodawprojectmididata)

Converts MIDI data into a `.dawproject` file format. This method takes binary MIDI data and converts it into a ZIP archive containing `project.xml` and `metadata.xml`, which is compatible with DAWs like Bitwig Studio.

- `$midiData` (string): The binary content of the MIDI file.

#### `dawProjectToMIDI($dawProjectData)`

[](#dawprojecttomididawprojectdata)

Converts a `.dawproject` file back into MIDI data. This method reads a `.dawproject` ZIP archive, parses its contents, and reconstructs the corresponding binary MIDI data.

- `$dawProjectData` (string): The binary content of the `.dawproject` file.

#### `dawProjectToPDF($dawProjectData, $songTitle, $composer, $targetChannelOrPartId, $singlePage)`

[](#dawprojecttopdfdawprojectdata-songtitle-composer-targetchannelorpartid-singlepage)

Converts a `.dawproject` file into a PDF file. This method first converts the `.dawproject` data into an intermediate MIDI format, and then renders that MIDI data to a PDF.

- `$dawProjectData` (string): The binary content of the `.dawproject` file.
- `$songTitle` (string): The title to be displayed on the sheet music.
- `$composer` (string): The composer's name to be displayed.
- `$targetChannelOrPartId` (int|string|null): The specific MIDI channel (1-16) or part ID to render.

#### `musicXMLToMIDI($musicXmlContent)`

[](#musicxmltomidimusicxmlcontent)

Converts a MusicXML string into a binary MIDI data string.

- `$musicXmlContent` (string): The MusicXML content as a string.

#### `midiToPDF($midiData, $songTitle, $composer, $targetChannelOrPartId, $mainMelody)`

[](#miditopdfmididata-songtitle-composer-targetchannelorpartid-mainmelody)

Renders MIDI data directly into a PDF sheet music string.

- `$midiData` (string): The binary content of a MIDI file.
- `$songTitle` (string): The title to be displayed on the sheet music.
- `$composer` (string): The composer's name to be displayed.
- `$targetChannelOrPartId` (int|string|null): The specific MIDI channel (1-16) or MusicXML part ID (e.g., "P1") to render. If null, the best part is auto-detected.
- `$mainMelody` (int): The MIDI channel number (1-16) considered to be the main melody, used to prioritize lyric display. Defaults to 3.

#### `musicXMLToPDF($xmlStr, $songTitle, $composer, $targetChannelOrPartId, $showLyric)`

[](#musicxmltopdfxmlstr-songtitle-composer-targetchannelorpartid-showlyric)

Renders MusicXML data into a PDF sheet music string.

- `$xmlStr` (string): The string content of a MusicXML file.
- `$songTitle` (string): The title to be displayed on the sheet music.
- `$composer` (string): The composer's name to be displayed.
- `$targetChannelOrPartId` (int|string|null): The specific MIDI channel (1-16) or MusicXML part ID (e.g., "P1") to render. If null, the best part is auto-detected.
- `$showLyric` (bool): If true, forces lyrics to be displayed if they exist in the selected part.

#### `midiToSVG($midiData, $songTitle, $composer, $targetChannelOrPartId, $mainMelody, $singlePage)`

[](#miditosvgmididata-songtitle-composer-targetchannelorpartid-mainmelody-singlepage)

#### `midiToSVG($midiData, $songTitle, $composer, $targetChannelOrPartId, $mainMelody, $singlePage, $mobile)`

[](#miditosvgmididata-songtitle-composer-targetchannelorpartid-mainmelody-singlepage-mobile)

Renders MIDI data directly into an interactive SVG image string.

- `$midiData` (string): The binary content of a MIDI file.
- `$songTitle` (string): The title to be displayed on the sheet music.
- `$composer` (string): The composer's name to be displayed.
- `$targetChannelOrPartId` (int|string|null): The specific MIDI channel (1-16) or MusicXML part ID (e.g., "P1") to render. If null, the best part is auto-detected.
- `$mainMelody` (int): The MIDI channel number (1-16) considered to be the main melody. Defaults to 3.
- `$singlePage` (bool): If true (default), generates a single continuous SVG. If false, generates stacked, page-like layouts within one SVG.
- `$mobile` (bool): If `true`, optimizes the layout for mobile devices by rendering one measure per system. Defaults to `false`.

#### `musicXMLToSVG($xmlStr, $songTitle, $composer, $targetChannelOrPartId, $showLyric, $singlePage, $mobile)`

[](#musicxmltosvgxmlstr-songtitle-composer-targetchannelorpartid-showlyric-singlepage-mobile)

Renders MusicXML data into an interactive SVG image string.

- `$xmlStr` (string): The string content of a MusicXML file.
- `$songTitle` (string): The title to be displayed on the sheet music.
- `$composer` (string): The composer's name to be displayed.
- `$targetChannelOrPartId` (int|string|null): The specific MIDI channel (1-16) or MusicXML part ID (e.g., "P1") to render. If null, the best part is auto-detected.
- `$showLyric` (bool): If true, forces lyrics to be displayed if they exist in the selected part.
- `$singlePage` (bool): If true (default), generates a single continuous SVG. If false, generates stacked, page-like layouts.
- `$mobile` (bool): If `true`, optimizes the layout for mobile devices by rendering one measure per system. Defaults to `false`.

#### `dawProjectToSVG($dawProjectData, $songTitle, $composer, $targetChannelOrPartId, $singlePage, $mobile)`

[](#dawprojecttosvgdawprojectdata-songtitle-composer-targetchannelorpartid-singlepage-mobile)

Converts a `.dawproject` file into an SVG image. This method first converts the `.dawproject` data into an intermediate MIDI format, and then renders that MIDI data to an SVG.

- `$dawProjectData` (string): The binary content of the `.dawproject` file.
- `$songTitle` (string): The title to be displayed on the sheet music.
- `$composer` (string): The composer's name to be displayed.
- `$targetChannelOrPartId` (int|string|null): The specific MIDI channel (1-16) or part ID to render.
- `$singlePage` (bool): If true, generates a single continuous SVG. If false, generates stacked pages.
- `$mobile` (bool): If `true`, optimizes the layout for mobile devices by rendering one measure per system. Defaults to `false`.

Examples
--------

[](#examples)

### Basic Example: Convert MIDI to PDF

[](#basic-example-convert-midi-to-pdf)

This example demonstrates the simplest use case: converting a MIDI file into a PDF.

```
