Skip to content

Instantly share code, notes, and snippets.

@st1vms
Created February 5, 2024 16:02
Show Gist options
  • Save st1vms/c07e24d4ae049062e5528eda58ab90b9 to your computer and use it in GitHub Desktop.
Save st1vms/c07e24d4ae049062e5528eda58ab90b9 to your computer and use it in GitHub Desktop.
Playing MIDI files with Pygame
Playing MIDI files with Pygame
@echo off
cd %~dp0
python -m pip install pip --upgrade
python -m pip install pygame --upgrade
python play_midi.py
pause
#!/usr/bin/env python3
"""Listen to a midi file using pygame"""
import os
import sys
from time import perf_counter
from traceback import print_exc
old_stdout = sys.stdout
with open(os.devnull, "w", encoding="utf-8") as devnull:
sys.stdout = devnull
import pygame
sys.stdout = old_stdout
def play_midi(file_path: str):
"""Play a midi file using pygame"""
pygame.mixer.init()
start_time = perf_counter()
try:
print(f"\nRiproduco il file -> {file_path}\n")
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
except KeyboardInterrupt:
pygame.mixer.music.stop()
pygame.mixer.quit()
end_time = perf_counter()
print(f"\nFine riproduzione MIDI in {round(end_time-start_time, 1)} secondi\n")
def ask_path(prompt: str) -> str | None:
"""Asks file path string"""
while True:
try:
fpath = input(prompt).strip()
except KeyboardInterrupt:
return None
if os.path.isfile(fpath):
return fpath
print("\nFile non trovato...\n")
def main() -> int:
"""main"""
while True:
try:
fpath = ask_path(
"\nInserire il percorso completo del file MIDI, e premere Invio\n>>"
)
if fpath is None:
return 0
play_midi(fpath)
except KeyboardInterrupt:
return 0
except Exception:
print_exc()
return 1
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment