Skip to content

Instantly share code, notes, and snippets.

@guitarmanvt
Created February 24, 2016 13:37
Show Gist options
  • Select an option

  • Save guitarmanvt/3b6a91cefb2f5c3098ed to your computer and use it in GitHub Desktop.

Select an option

Save guitarmanvt/3b6a91cefb2f5c3098ed to your computer and use it in GitHub Desktop.
Play MIDI files using pygame
# play .mid music files using PyGame on your computer's sound card
# PyGame is free from: http://www.pygame.org/news.html
# tested with Python25 and PyGame171 vegaseat 27aug2007
import pygame
def play_music(music_file):
"""
stream music with mixer.music module in blocking manner
this will stream the sound from disk while playing
"""
clock = pygame.time.Clock()
try:
pygame.mixer.music.load(music_file)
print "Music file %s loaded!" % music_file
except pygame.error:
print "File %s not found! (%s)" % (music_file, pygame.get_error())
return
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
# check if playback has finished
clock.tick(30)
# pick a midi music file you have ...
# (if not in working folder use full path)
import os
def music_files():
music_dir = "/Users/janderson/Music/MIDI/"
midi_files = os.listdir(music_dir)
for one in midi_files:
yield music_dir + one
freq = 44100 # audio CD quality
bitsize = -16 # unsigned 16 bit
channels = 2 # 1 is mono, 2 is stereo
buffer = 1024 # number of samples
pygame.mixer.init(freq, bitsize, channels, buffer)
# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.8)
for music_file in music_files():
try:
play_music(music_file)
except KeyboardInterrupt:
# if user hits Ctrl/C then exit
# (works only in console mode)
while True:
action = raw_input('Enter Q to Quit, Enter to Skip. ').lower()
if action == 'q':
pygame.mixer.music.fadeout(1000)
pygame.mixer.music.stop()
raise SystemExit
else:
break
@mateuszdorobek
Copy link
Copy Markdown

Hey do you have any idea, how to pause and unpause music.
pygame.mixer.music.pause()
This isn't working, and I've read that it happens only, whem using MIDI files.

@pfsquirrel
Copy link
Copy Markdown

To pause and unpause, I use Linux command-line tools. To pause, press CTL-Z. To unpause, run fg.

@pfsquirrel
Copy link
Copy Markdown

pfsquirrel commented Nov 8, 2020

Updated for Python 3:

# play .mid music files using PyGame on your computer's sound card
# PyGame is free from: http://www.pygame.org/news.html
# tested with Python25 and PyGame171      vegaseat     27aug2007
import pygame
def play_music(music_file):
    """
    stream music with mixer.music module in blocking manner
    this will stream the sound from disk while playing
    """
    clock = pygame.time.Clock()
    try:
        pygame.mixer.music.load(music_file)
        print("Music file %s loaded!" % music_file)
    except pygame.error:
        print("File %s not found! (%s)" % (music_file, pygame.get_error()))
        return
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        # check if playback has finished
        clock.tick(30)
# pick a midi music file you have ...
# (if not in working folder use full path)

import os
def music_files():
    music_dir = "/Users/jsa/Music/MIDI/"
    midi_files = os.listdir(music_dir)
    for one in midi_files:
        yield music_dir + one


freq = 44100    # audio CD quality
bitsize = -16   # unsigned 16 bit
channels = 2    # 1 is mono, 2 is stereo
buffer = 1024    # number of samples
pygame.mixer.init(freq, bitsize, channels, buffer)
# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.8)
for music_file in music_files():
    try:
        play_music(music_file)
    except KeyboardInterrupt:
        # if user hits Ctrl/C then exit
        # (works only in console mode)
        while True:
            action = input('Enter Q to Quit, Enter to Skip. ').lower()
            if action == 'q':
                pygame.mixer.music.fadeout(1000)
                pygame.mixer.music.stop()
                raise SystemExit
            else:
                break

I installed it locally using poetry. Here's the pyproject.toml:

[tool.poetry]
name = "playmidi"
version = "0.1.0"
description = ""
authors = ["John Anderson <john@andersoninnovative.com>"]

[tool.poetry.dependencies]
python = "^3.9"
pygame = "^2.0.0"

[tool.poetry.dev-dependencies]

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

@TheHumanistX
Copy link
Copy Markdown

Can you stream a midi from a URL or only play local midi?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment