Certainly! Below is an advanced Python script that converts MIDI files containing piano parts into text-based piano sheets. This script utilizes the music21 library, which is a powerful toolkit for computer-aided musicology.
Overview
-
Dependencies:
music21: For parsing MIDI files and handling musical data.
argparse: For handling command-line arguments.
os: For file path operations.
-
Functionality:
- MIDI Parsing: The script reads a MIDI file and parses its contents.
- Piano Track Extraction: It identifies and extracts piano tracks based on MIDI program numbers.
- Textual Representation: Converts the extracted piano parts into a readable text format, detailing measures, beats, notes, and their durations.
- Output: Saves the textual piano sheet to a
.txt file.
-
Usage:
- Ensure that the required libraries are installed.
- Run the script via the command line, providing the path to the MIDI file.
- The script will generate a corresponding text file with the piano sheet.
Installation
Before running the script, ensure you have the necessary libraries installed. You can install them using pip:
pip install music21
The Script
import argparse
import os
from music21 import converter, instrument, note, chord, stream, tempo, meter
def extract_piano_parts(midi_stream):
"""
Extract piano instruments from the MIDI stream.
"""
piano_parts = []
for part in midi_stream.parts:
# Check if the part has a Piano instrument
instruments = part.getInstruments()
for ins in instruments:
if isinstance(ins, instrument.Piano):
piano_parts.append(part)
break
else:
# Sometimes piano parts might not have instrument specified
# Assume grand piano (program number 0) by default
if part.getInstrument().instrumentName.lower() == "piano" or part.getInstrument().instrumentName.lower() == "acoustic grand piano":
piano_parts.append(part)
return piano_parts
def get_text_piano_sheet(midi_path):
"""
Convert MIDI file to a text-based piano sheet.
"""
# Load the MIDI file
midi_stream = converter.parse(midi_path)
# Extract piano parts
piano_parts = extract_piano_parts(midi_stream)
if not piano_parts:
print("No piano parts found in the MIDI file.")
return
# Create a new stream for piano
piano_stream = stream.Stream()
for part in piano_parts:
piano_stream.append(part)
piano_stream = piano_stream.flat
# Get key signature
key = piano_stream.analyze('key')
# Get time signature
ts = piano_stream.recurse().getElementsByClass(meter.TimeSignature)
if ts:
time_signature = ts[0].ratioString
else:
time_signature = "4/4" # Default
# Get tempo
tempos = piano_stream.recurse().getElementsByClass(tempo.MetronomeMark)
if tempos:
bpm = tempos[0].number
else:
bpm = 120 # Default
# Prepare the text sheet
text_sheet = []
text_sheet.append("=== Piano Sheet ===")
text_sheet.append(f"Key Signature: {key}")
text_sheet.append(f"Time Signature: {time_signature}")
text_sheet.append(f"Tempo: {bpm} BPM\n")
measures = piano_stream.makeMeasures().getElementsByClass(stream.Measure)
for measure in measures:
measure_number = measure.measureNumber
text_sheet.append(f"Measure {measure_number}:")
for elem in measure.notesAndRests:
if isinstance(elem, note.Note):
n = elem.nameWithOctave
dur = elem.duration.type
offset = elem.offset
text_sheet.append(f" Note: {n}, Duration: {dur}, Offset: {offset}")
elif isinstance(elem, chord.Chord):
c = '.'.join(n.nameWithOctave for n in elem.notes)
dur = elem.duration.type
offset = elem.offset
text_sheet.append(f" Chord: {c}, Duration: {dur}, Offset: {offset}")
elif isinstance(elem, note.Rest):
dur = elem.duration.type
offset = elem.offset
text_sheet.append(f" Rest, Duration: {dur}, Offset: {offset}")
text_sheet.append("") # Empty line after each measure
return "\n".join(text_sheet)
def main():
parser = argparse.ArgumentParser(description="Convert MIDI files with piano parts into text-based piano sheets.")
parser.add_argument("midi_file", help="Path to the MIDI file.")
parser.add_argument("-o", "--output", help="Output text file path. If not provided, uses the same name with .txt extension.")
args = parser.parse_args()
midi_path = args.midi_file
if not os.path.isfile(midi_path):
print(f"Error: File '{midi_path}' does not exist.")
return
text_sheet = get_text_piano_sheet(midi_path)
if text_sheet:
if args.output:
output_path = args.output
else:
base, _ = os.path.splitext(midi_path)
output_path = base + ".txt"
with open(output_path, "w") as f:
f.write(text_sheet)
print(f"Text piano sheet saved to '{output_path}'.")
if __name__ == "__main__":
main()
How It Works
-
Parsing the MIDI File:
- The script uses
music21.converter.parse to read the MIDI file and convert it into a music21 stream object.
-
Extracting Piano Parts:
- It iterates through the parts of the MIDI stream to identify those that are designated as piano instruments based on the instrument name or MIDI program number.
- If no specific instrument is found, it defaults to the assumption that tracks without explicit instruments might contain piano data.
-
Analyzing Musical Elements:
- Key Signature: Determined using
analyze('key').
- Time Signature: Extracted from the first time signature found; defaults to 4/4 if none is specified.
- Tempo: Extracted from the first tempo mark; defaults to 120 BPM if none is specified.
-
Generating the Textual Sheet:
- The script processes each measure, listing the notes, chords, rests, their durations (e.g., quarter, half), and their offsets within the measure.
- Chords are represented by concatenating the individual note names with dots.
-
Output:
- The generated text is either printed to the console or saved to a specified text file.
Running the Script
-
Save the Script:
- Save the script to a file, for example,
midi_to_text_piano.py.
-
Execute via Command Line:
- Open your terminal or command prompt.
- Navigate to the directory containing the script.
- Run the script using Python, providing the path to your MIDI file.
python midi_to_text_piano.py path/to/your/file.mid
- Specify Output File (Optional):
- To specify a custom output file, use the
-o or --output flag.
python midi_to_text_piano.py path/to/your/file.mid -o output_piano_sheet.txt
- Output:
- The script will generate a text file containing the piano sheet. Here's an example of what the output might look like:
=== Piano Sheet ===
Key Signature: C major
Time Signature: 4/4
Tempo: 120 BPM
Measure 1:
Note: C4, Duration: quarter, Offset: 0.0
Note: E4, Duration: quarter, Offset: 1.0
Note: G4, Duration: quarter, Offset: 2.0
Rest, Duration: quarter, Offset: 3.0
Measure 2:
Chord: F4.A4.C5, Duration: half, Offset: 0.0
Note: G4, Duration: half, Offset: 2.0
...
Notes and Considerations
-
Complex MIDI Files: For MIDI files with multiple piano tracks, layered instruments, or complex arrangements, the script may need further refinement to accurately represent all nuances.
-
Enhancements:
- Error Handling: Improve the script to handle edge cases and provide more detailed error messages.
- Enhanced Formatting: Incorporate better formatting for readability, such as aligning notes or representing rhythms more clearly.
- Support for Dynamics and Articulations: Extend the script to capture dynamics (e.g., forte, piano) and articulations if present in the MIDI.
-
Performance: For very large MIDI files, processing might take longer. Optimizations can be made if necessary.
-
Compatibility: Ensure that the MIDI files you intend to convert reliably specify instruments to allow accurate extraction of piano parts.
Conclusion
This script provides a foundational tool for converting MIDI piano files into a readable text format, which can be useful for various applications such as educational purposes, analysis, or generating simplified sheet music. Depending on your specific needs, you can further enhance and customize the script to better fit your requirements.