Reputation: 45
I've been working on a sound-related Pygame project using pygame.mixer
, and I've come across a problem I can't seem to solve. I'm unable to open any sound file that I've tried (.mp3 and .midi).
I'm using Python 3 on PyCharm 2018.3. My Pygame is mostly up-to-date (version 1.9.3). I've tried using the full path, I've done pygame.init()
, mixer.init()
, and I'm completely stuck.
This is my code:
import pygame
from pygame import mixer
pygame.init()
mixer.init(44100, 16, 2, 4096)
f = mixer.Sound("output.midi")
f.play()
print(bool(mixer.get_busy()))
while mixer.get_busy():
pass
This is the error (the ...
in the file cover the actual traceback):
Traceback (most recent call last):
File "/home/.../note.py", line 27, in <module>
f = mixer.Sound("output.midi")
pygame.error: Unable to open file 'output.midi'
The program is supposed to open a .midi
file created in another part of the program (which I've commented out) and play it until it is finished. Instead, I just get the error and no sound plays.
Upvotes: 1
Views: 496
Reputation: 1978
O course, you can play MIDI files with pygame. The extension of a MIdI-file is .mid
(not .midi
as in your code). This works for me:
import pygame
def play_MIDI_pygame(midi_file):
freq = 44100 # audio CD quality
bitsize = -16 # unsigned 16 bit
channels = 2 # 1 is mono, 2 is stereo
buffer = 1024 # number of samples
clock = pygame.time.Clock()
pygame.mixer.init(freq, bitsize, channels, buffer)
pygame.mixer.music.set_volume(0.8) # volume 0 to 1.0
pygame.mixer.music.load(midi_file) # read the midi file
pygame.mixer.music.play() # play the music
while pygame.mixer.music.get_busy(): # check if playback has finished
clock.tick(30)
midi_file = 'myMidi.mid'
play_MIDI_pygame(midi_file)
Upvotes: 1
Reputation: 385098
A MIDI file is not "a sound file"; it is basically digital sheet music. You'd need a MIDI synthesiser to generate sound from it.
And a MP3 is compressed with an algorithm; it's not a sequence of sound samples.
From the PyGame.Mixer documentation:
The Sound can be loaded from an OGG audio file or from an uncompressed WAV.
In short, you're using the wrong tool for the job.
Upvotes: 1