Generate MIDI file and play it without saving it to disk

我与影子孤独终老i 提交于 2019-12-11 01:45:50

问题


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:


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!"


来源:https://stackoverflow.com/questions/27279864/generate-midi-file-and-play-it-without-saving-it-to-disk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!