Skip to content

update parser api #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ Usage Example

import adafruit_midi_parser

parser = adafruit_midi_parser.MIDIParser()

midi_file = "/song.mid"

print("MIDI File Analyzer")
Expand All @@ -102,9 +104,8 @@ Usage Example
file_list = os.listdir("/")
if midi_file[1:] in file_list:
print(f"\nFound MIDI file {midi_file}")
parser = adafruit_midi_parser.MIDIParser(midi_file)
print("\nParsing MIDI file...")
parser.parse()
parser.parse(midi_file)
print("\nMIDI File Information:")
print("=====================")
print(f"Format Type: {parser.format_type}")
Expand Down
22 changes: 19 additions & 3 deletions adafruit_midi_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ class MIDIParser:
:param str filename: Path to the MIDI file
"""

def __init__(self, filename: str) -> None:
def __init__(self) -> None:
"""
Initialize the MIDI parser.

:param str filename: Path to the MIDI file
"""
self._filename: str = filename
self._filename: Optional[str] = None
self._events: List[Dict[str, Any]] = []
self._tempo: int = 500000 # Default tempo (microseconds per quarter note)
self._ticks_per_beat: int = 480 # Default time division
Expand Down Expand Up @@ -188,7 +188,21 @@ def _read_variable_length(data: bytes, offset: int) -> Tuple[int, int]:
break
return value, offset

def parse(self, debug: bool = False) -> bool: # noqa: PLR0912 PLR0915 PLR0914
def clear(self) -> None:
"""
Clear all parsed data and reset the parser state.
"""
self._filename = None
self._events = []
self._tempo = 500000 # Default tempo
self._ticks_per_beat = 480 # Default division
self._current_event_index = 0
self._format_type = 0
self._num_tracks = 0
self._parsed = False
self._last_absolute_time = 0

def parse(self, filename: str, debug: bool = False) -> bool: # noqa: PLR0912 PLR0915 PLR0914
"""
Parse the MIDI file and extract events.

Expand All @@ -197,6 +211,8 @@ def parse(self, debug: bool = False) -> bool: # noqa: PLR0912 PLR0915 PLR0914
:rtype: bool
:raises MIDIParseError: If the file doesn't exist or is not a valid MIDI file
"""
self.clear()
self._filename = filename
try: # noqa: PLR1702
with open(self._filename, "rb") as file:
data = file.read()
Expand Down
4 changes: 2 additions & 2 deletions examples/midi_parser_player_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ def on_playback_complete(self): # noqa: PLR6301
print(f"Found MIDI file {midi_file}")

# Create a MIDIParser instance
parser = adafruit_midi_parser.MIDIParser(midi_file)
parser = adafruit_midi_parser.MIDIParser()

# Parse the file
parser.parse()
parser.parse(midi_file)
print(f"Successfully parsed! Found {len(parser.events)} events.")
print(f"BPM: {parser.bpm:.1f}")
print(f"Note Count: {parser.note_count}")
Expand Down
4 changes: 2 additions & 2 deletions examples/midi_parser_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
# Check if the file exists
if midi_file[1:] in file_list:
print(f"\nFound MIDI file {midi_file}")
parser = adafruit_midi_parser.MIDIParser(midi_file)
parser = adafruit_midi_parser.MIDIParser()
print("\nParsing MIDI file...")
parser.parse()
parser.parse(midi_file)
print("\nMIDI File Information:")
print("=====================")
print(f"Format Type: {parser.format_type}")
Expand Down