Generate MIDI file and play it without saving it t

2019-07-19 01:44发布

I found this module that can create midi files.

I can play the output file using pygame mixer.music easily, but if I try to play without having to save to a file(play the object) it doesn't work, I get

pygame.error: Couldn't read from RWops

.

I tried using StringIO with no success. I get the same error above.

Does anyone one know any module that can play MIDI objects, maybe create them too?

1条回答
狗以群分
2楼-- · 2019-07-19 02:35

did you remember to rewind your StringIO buffer?

I went through all the steps you did, and got the same error. Then I tracked down the RWops library at sourceforge (dated 2006) and was ready to blame it.

then after succeeding with objects in module tempfile, I tried ByteIO from module IO. They both worked, but I did a seek(0) with them before the load.

So I went back to StringIO, and did a seek(0) before the load, and success!!

Here's an edited and condensed modification of the sample from midutil:

from midiutil.MidiFile import MIDIFile
from StringIO import StringIO

# CREATE MEMORY FILE

memFile = StringIO()
MyMIDI = MIDIFile(1)
track = 0
time = 0
channel = 0
pitch = 60
duration = 1
volume = 100
MyMIDI.addTrackName(track,time,"Sample Track")
MyMIDI.addTempo(track,time,120)

# WRITE A SCALE

MyMIDI.addNote(track,channel,pitch,time,duration,volume)
for notestep in [2,2,1,2,2,2,1]:
    time += duration
    pitch += notestep
    MyMIDI.addNote(track,channel,pitch,time,duration,volume)
MyMIDI.writeFile(memFile)

# PLAYBACK

import pygame
import pygame.mixer
from time import sleep

pygame.init()
pygame.mixer.init()
memFile.seek(0)  # THIS IS CRITICAL, OTHERWISE YOU GET THAT ERROR!
pygame.mixer.music.load(memFile)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
    sleep(1)
print "Done!"
查看更多
登录 后发表回答