midi.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. """pygame.midi
  2. pygame module for interacting with midi input and output.
  3. The midi module can send output to midi devices, and get input
  4. from midi devices. It can also list midi devices on the system.
  5. Including real midi devices, and virtual ones.
  6. It uses the portmidi library. Is portable to which ever platforms
  7. portmidi supports (currently windows, OSX, and linux).
  8. This uses pyportmidi for now, but may use its own bindings at some
  9. point in the future. The pyportmidi bindings are included with pygame.
  10. New in pygame 1.9.0.
  11. """
  12. #TODO:
  13. # - finish writing tests.
  14. # - likely as interactive tests... so you'd need to plug in a midi device.
  15. # - create a background thread version for input threads.
  16. # - that can automatically inject input into the event queue
  17. # once the input object is running. Like joysticks.
  18. import atexit
  19. import math
  20. import pygame
  21. import pygame.locals
  22. #
  23. MIDIIN = pygame.locals.USEREVENT + 10
  24. MIDIOUT = pygame.locals.USEREVENT + 11
  25. _init = False
  26. _pypm = None
  27. __all__ = [
  28. "Input",
  29. "MIDIIN",
  30. "MIDIOUT",
  31. "MidiException",
  32. "Output",
  33. "get_count",
  34. "get_default_input_id",
  35. "get_default_output_id",
  36. "get_device_info",
  37. "init",
  38. "midis2events",
  39. "quit",
  40. "get_init",
  41. "time",
  42. "frequency_to_midi",
  43. "midi_to_frequency",
  44. "midi_to_ansi_note",
  45. ]
  46. __theclasses__ = ["Input", "Output"]
  47. def init():
  48. """initialize the midi module
  49. pygame.midi.init(): return None
  50. Call the initialisation function before using the midi module.
  51. It is safe to call this more than once.
  52. """
  53. global _init, _pypm
  54. if not _init:
  55. import pygame.pypm
  56. _pypm = pygame.pypm
  57. _pypm.Initialize()
  58. _init = True
  59. atexit.register(quit)
  60. def quit():
  61. """uninitialize the midi module
  62. pygame.midi.quit(): return None
  63. Called automatically atexit if you don't call it.
  64. It is safe to call this function more than once.
  65. """
  66. global _init, _pypm
  67. if _init:
  68. # TODO: find all Input and Output classes and close them first?
  69. _pypm.Terminate()
  70. _init = False
  71. del _pypm
  72. #del pygame._pypm
  73. def get_init():
  74. """returns True if the midi module is currently initialized
  75. pygame.midi.get_init(): return bool
  76. Returns True if the pygame.midi module is currently initialized.
  77. New in pygame 1.9.5.
  78. """
  79. return _init
  80. def _check_init():
  81. if not _init:
  82. raise RuntimeError("pygame.midi not initialised.")
  83. def get_count():
  84. """gets the number of devices.
  85. pygame.midi.get_count(): return num_devices
  86. Device ids range from 0 to get_count() -1
  87. """
  88. _check_init()
  89. return _pypm.CountDevices()
  90. def get_default_input_id():
  91. """gets default input device number
  92. pygame.midi.get_default_input_id(): return default_id
  93. Return the default device ID or -1 if there are no devices.
  94. The result can be passed to the Input()/Ouput() class.
  95. On the PC, the user can specify a default device by
  96. setting an environment variable. For example, to use device #1.
  97. set PM_RECOMMENDED_INPUT_DEVICE=1
  98. The user should first determine the available device ID by using
  99. the supplied application "testin" or "testout".
  100. In general, the registry is a better place for this kind of info,
  101. and with USB devices that can come and go, using integers is not
  102. very reliable for device identification. Under Windows, if
  103. PM_RECOMMENDED_OUTPUT_DEVICE (or PM_RECOMMENDED_INPUT_DEVICE) is
  104. *NOT* found in the environment, then the default device is obtained
  105. by looking for a string in the registry under:
  106. HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Input_Device
  107. and HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Output_Device
  108. for a string. The number of the first device with a substring that
  109. matches the string exactly is returned. For example, if the string
  110. in the registry is "USB", and device 1 is named
  111. "In USB MidiSport 1x1", then that will be the default
  112. input because it contains the string "USB".
  113. In addition to the name, get_device_info() returns "interf", which
  114. is the interface name. (The "interface" is the underlying software
  115. system or API used by PortMidi to access devices. Examples are
  116. MMSystem, DirectX (not implemented), ALSA, OSS (not implemented), etc.)
  117. At present, the only Win32 interface is "MMSystem", the only Linux
  118. interface is "ALSA", and the only Max OS X interface is "CoreMIDI".
  119. To specify both the interface and the device name in the registry,
  120. separate the two with a comma and a space, e.g.:
  121. MMSystem, In USB MidiSport 1x1
  122. In this case, the string before the comma must be a substring of
  123. the "interf" string, and the string after the space must be a
  124. substring of the "name" name string in order to match the device.
  125. Note: in the current release, the default is simply the first device
  126. (the input or output device with the lowest PmDeviceID).
  127. """
  128. return _pypm.GetDefaultInputDeviceID()
  129. def get_default_output_id():
  130. """gets default output device number
  131. pygame.midi.get_default_output_id(): return default_id
  132. Return the default device ID or -1 if there are no devices.
  133. The result can be passed to the Input()/Ouput() class.
  134. On the PC, the user can specify a default device by
  135. setting an environment variable. For example, to use device #1.
  136. set PM_RECOMMENDED_OUTPUT_DEVICE=1
  137. The user should first determine the available device ID by using
  138. the supplied application "testin" or "testout".
  139. In general, the registry is a better place for this kind of info,
  140. and with USB devices that can come and go, using integers is not
  141. very reliable for device identification. Under Windows, if
  142. PM_RECOMMENDED_OUTPUT_DEVICE (or PM_RECOMMENDED_INPUT_DEVICE) is
  143. *NOT* found in the environment, then the default device is obtained
  144. by looking for a string in the registry under:
  145. HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Input_Device
  146. and HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Output_Device
  147. for a string. The number of the first device with a substring that
  148. matches the string exactly is returned. For example, if the string
  149. in the registry is "USB", and device 1 is named
  150. "In USB MidiSport 1x1", then that will be the default
  151. input because it contains the string "USB".
  152. In addition to the name, get_device_info() returns "interf", which
  153. is the interface name. (The "interface" is the underlying software
  154. system or API used by PortMidi to access devices. Examples are
  155. MMSystem, DirectX (not implemented), ALSA, OSS (not implemented), etc.)
  156. At present, the only Win32 interface is "MMSystem", the only Linux
  157. interface is "ALSA", and the only Max OS X interface is "CoreMIDI".
  158. To specify both the interface and the device name in the registry,
  159. separate the two with a comma and a space, e.g.:
  160. MMSystem, In USB MidiSport 1x1
  161. In this case, the string before the comma must be a substring of
  162. the "interf" string, and the string after the space must be a
  163. substring of the "name" name string in order to match the device.
  164. Note: in the current release, the default is simply the first device
  165. (the input or output device with the lowest PmDeviceID).
  166. """
  167. _check_init()
  168. return _pypm.GetDefaultOutputDeviceID()
  169. def get_device_info(an_id):
  170. """ returns information about a midi device
  171. pygame.midi.get_device_info(an_id): return (interf, name, input, output, opened)
  172. interf - a text string describing the device interface, eg 'ALSA'.
  173. name - a text string for the name of the device, eg 'Midi Through Port-0'
  174. input - 0, or 1 if the device is an input device.
  175. output - 0, or 1 if the device is an output device.
  176. opened - 0, or 1 if the device is opened.
  177. If the id is out of range, the function returns None.
  178. """
  179. _check_init()
  180. return _pypm.GetDeviceInfo(an_id)
  181. class Input(object):
  182. """Input is used to get midi input from midi devices.
  183. Input(device_id)
  184. Input(device_id, buffer_size)
  185. buffer_size - the number of input events to be buffered waiting to
  186. be read using Input.read()
  187. """
  188. def __init__(self, device_id, buffer_size=4096):
  189. """
  190. The buffer_size specifies the number of input events to be buffered
  191. waiting to be read using Input.read().
  192. """
  193. _check_init()
  194. if device_id == -1:
  195. raise MidiException("Device id is -1, not a valid output id. -1 usually means there were no default Output devices.")
  196. try:
  197. r = get_device_info(device_id)
  198. except TypeError:
  199. raise TypeError("an integer is required")
  200. except OverflowError:
  201. raise OverflowError("long int too large to convert to int")
  202. # and now some nasty looking error checking, to provide nice error
  203. # messages to the kind, lovely, midi using people of whereever.
  204. if r:
  205. interf, name, input, output, opened = r
  206. if input:
  207. try:
  208. self._input = _pypm.Input(device_id, buffer_size)
  209. except TypeError:
  210. raise TypeError("an integer is required")
  211. self.device_id = device_id
  212. elif output:
  213. raise MidiException("Device id given is not a valid input id, it is an output id.")
  214. else:
  215. raise MidiException("Device id given is not a valid input id.")
  216. else:
  217. raise MidiException("Device id invalid, out of range.")
  218. def _check_open(self):
  219. if self._input is None:
  220. raise MidiException("midi not open.")
  221. def close(self):
  222. """ closes a midi stream, flushing any pending buffers.
  223. Input.close(): return None
  224. PortMidi attempts to close open streams when the application
  225. exits -- this is particularly difficult under Windows.
  226. """
  227. _check_init()
  228. if not (self._input is None):
  229. self._input.Close()
  230. self._input = None
  231. def read(self, num_events):
  232. """reads num_events midi events from the buffer.
  233. Input.read(num_events): return midi_event_list
  234. Reads from the Input buffer and gives back midi events.
  235. [[[status,data1,data2,data3],timestamp],
  236. [[status,data1,data2,data3],timestamp],...]
  237. """
  238. _check_init()
  239. self._check_open()
  240. return self._input.Read(num_events)
  241. def poll(self):
  242. """returns true if there's data, or false if not.
  243. Input.poll(): return Bool
  244. raises a MidiException on error.
  245. """
  246. _check_init()
  247. self._check_open()
  248. r = self._input.Poll()
  249. if r == _pypm.TRUE:
  250. return True
  251. elif r == _pypm.FALSE:
  252. return False
  253. else:
  254. err_text = GetErrorText(r)
  255. raise MidiException( (r, err_text) )
  256. class Output(object):
  257. """Output is used to send midi to an output device
  258. Output(device_id)
  259. Output(device_id, latency = 0)
  260. Output(device_id, buffer_size = 4096)
  261. Output(device_id, latency, buffer_size)
  262. The buffer_size specifies the number of output events to be
  263. buffered waiting for output. (In some cases -- see below --
  264. PortMidi does not buffer output at all and merely passes data
  265. to a lower-level API, in which case buffersize is ignored.)
  266. latency is the delay in milliseconds applied to timestamps to determine
  267. when the output should actually occur. (If latency is < 0, 0 is
  268. assumed.)
  269. If latency is zero, timestamps are ignored and all output is delivered
  270. immediately. If latency is greater than zero, output is delayed until
  271. the message timestamp plus the latency. (NOTE: time is measured
  272. relative to the time source indicated by time_proc. Timestamps are
  273. absolute, not relative delays or offsets.) In some cases, PortMidi
  274. can obtain better timing than your application by passing timestamps
  275. along to the device driver or hardware. Latency may also help you
  276. to synchronize midi data to audio data by matching midi latency to
  277. the audio buffer latency.
  278. """
  279. def __init__(self, device_id, latency = 0, buffer_size = 4096):
  280. """Output(device_id)
  281. Output(device_id, latency = 0)
  282. Output(device_id, buffer_size = 4096)
  283. Output(device_id, latency, buffer_size)
  284. The buffer_size specifies the number of output events to be
  285. buffered waiting for output. (In some cases -- see below --
  286. PortMidi does not buffer output at all and merely passes data
  287. to a lower-level API, in which case buffersize is ignored.)
  288. latency is the delay in milliseconds applied to timestamps to determine
  289. when the output should actually occur. (If latency is < 0, 0 is
  290. assumed.)
  291. If latency is zero, timestamps are ignored and all output is delivered
  292. immediately. If latency is greater than zero, output is delayed until
  293. the message timestamp plus the latency. (NOTE: time is measured
  294. relative to the time source indicated by time_proc. Timestamps are
  295. absolute, not relative delays or offsets.) In some cases, PortMidi
  296. can obtain better timing than your application by passing timestamps
  297. along to the device driver or hardware. Latency may also help you
  298. to synchronize midi data to audio data by matching midi latency to
  299. the audio buffer latency.
  300. """
  301. _check_init()
  302. self._aborted = 0
  303. if device_id == -1:
  304. raise MidiException("Device id is -1, not a valid output id. -1 usually means there were no default Output devices.")
  305. try:
  306. r = get_device_info(device_id)
  307. except TypeError:
  308. raise TypeError("an integer is required")
  309. except OverflowError:
  310. raise OverflowError("long int too large to convert to int")
  311. # and now some nasty looking error checking, to provide nice error
  312. # messages to the kind, lovely, midi using people of whereever.
  313. if r:
  314. interf, name, input, output, opened = r
  315. if output:
  316. try:
  317. self._output = _pypm.Output(device_id, latency)
  318. except TypeError:
  319. raise TypeError("an integer is required")
  320. self.device_id = device_id
  321. elif input:
  322. raise MidiException("Device id given is not a valid output id, it is an input id.")
  323. else:
  324. raise MidiException("Device id given is not a valid output id.")
  325. else:
  326. raise MidiException("Device id invalid, out of range.")
  327. def _check_open(self):
  328. if self._output is None:
  329. raise MidiException("midi not open.")
  330. if self._aborted:
  331. raise MidiException("midi aborted.")
  332. def close(self):
  333. """ closes a midi stream, flushing any pending buffers.
  334. Output.close(): return None
  335. PortMidi attempts to close open streams when the application
  336. exits -- this is particularly difficult under Windows.
  337. """
  338. _check_init()
  339. if not (self._output is None):
  340. self._output.Close()
  341. self._output = None
  342. def abort(self):
  343. """terminates outgoing messages immediately
  344. Output.abort(): return None
  345. The caller should immediately close the output port;
  346. this call may result in transmission of a partial midi message.
  347. There is no abort for Midi input because the user can simply
  348. ignore messages in the buffer and close an input device at
  349. any time.
  350. """
  351. _check_init()
  352. if self._output:
  353. self._output.Abort()
  354. self._aborted = 1
  355. def write(self, data):
  356. """writes a list of midi data to the Output
  357. Output.write(data)
  358. writes series of MIDI information in the form of a list:
  359. write([[[status <,data1><,data2><,data3>],timestamp],
  360. [[status <,data1><,data2><,data3>],timestamp],...])
  361. <data> fields are optional
  362. example: choose program change 1 at time 20000 and
  363. send note 65 with velocity 100 500 ms later.
  364. write([[[0xc0,0,0],20000],[[0x90,60,100],20500]])
  365. notes:
  366. 1. timestamps will be ignored if latency = 0.
  367. 2. To get a note to play immediately, send MIDI info with
  368. timestamp read from function Time.
  369. 3. understanding optional data fields:
  370. write([[[0xc0,0,0],20000]]) is equivalent to
  371. write([[[0xc0],20000]])
  372. Can send up to 1024 elements in your data list, otherwise an
  373. IndexError exception is raised.
  374. """
  375. _check_init()
  376. self._check_open()
  377. self._output.Write(data)
  378. def write_short(self, status, data1=0, data2=0):
  379. """write_short(status <, data1><, data2>)
  380. Output.write_short(status)
  381. Output.write_short(status, data1 = 0, data2 = 0)
  382. output MIDI information of 3 bytes or less.
  383. data fields are optional
  384. status byte could be:
  385. 0xc0 = program change
  386. 0x90 = note on
  387. etc.
  388. data bytes are optional and assumed 0 if omitted
  389. example: note 65 on with velocity 100
  390. write_short(0x90,65,100)
  391. """
  392. _check_init()
  393. self._check_open()
  394. self._output.WriteShort(status, data1, data2)
  395. def write_sys_ex(self, when, msg):
  396. """writes a timestamped system-exclusive midi message.
  397. Output.write_sys_ex(when, msg)
  398. msg - can be a *list* or a *string*
  399. when - a timestamp in miliseconds
  400. example:
  401. (assuming o is an onput MIDI stream)
  402. o.write_sys_ex(0,'\\xF0\\x7D\\x10\\x11\\x12\\x13\\xF7')
  403. is equivalent to
  404. o.write_sys_ex(pygame.midi.time(),
  405. [0xF0,0x7D,0x10,0x11,0x12,0x13,0xF7])
  406. """
  407. _check_init()
  408. self._check_open()
  409. self._output.WriteSysEx(when, msg)
  410. def note_on(self, note, velocity, channel=0):
  411. """turns a midi note on. Note must be off.
  412. Output.note_on(note, velocity, channel=0)
  413. note is an integer from 0 to 127
  414. velocity is an integer from 0 to 127
  415. channel is an integer from 0 to 15
  416. Turn a note on in the output stream. The note must already
  417. be off for this to work correctly.
  418. """
  419. if not (0 <= channel <= 15):
  420. raise ValueError("Channel not between 0 and 15.")
  421. self.write_short(0x90 + channel, note, velocity)
  422. def note_off(self, note, velocity=0, channel=0):
  423. """turns a midi note off. Note must be on.
  424. Output.note_off(note, velocity=0, channel=0)
  425. note is an integer from 0 to 127
  426. velocity is an integer from 0 to 127 (release velocity)
  427. channel is an integer from 0 to 15
  428. Turn a note off in the output stream. The note must already
  429. be on for this to work correctly.
  430. """
  431. if not (0 <= channel <= 15):
  432. raise ValueError("Channel not between 0 and 15.")
  433. self.write_short(0x80 + channel, note, velocity)
  434. def set_instrument(self, instrument_id, channel=0):
  435. """select an instrument for a channel, with a value between 0 and 127
  436. Output.set_instrument(instrument_id, channel=0)
  437. Also called "patch change" or "program change".
  438. """
  439. if not (0 <= instrument_id <= 127):
  440. raise ValueError("Undefined instrument id: %d" % instrument_id)
  441. if not (0 <= channel <= 15):
  442. raise ValueError("Channel not between 0 and 15.")
  443. self.write_short(0xc0 + channel, instrument_id)
  444. def pitch_bend(self, value=0, channel=0):
  445. """modify the pitch of a channel.
  446. Output.pitch_bend(value=0, channel=0)
  447. Adjust the pitch of a channel. The value is a signed integer
  448. from -8192 to +8191. For example, 0 means "no change", +4096 is
  449. typically a semitone higher, and -8192 is 1 whole tone lower (though
  450. the musical range corresponding to the pitch bend range can also be
  451. changed in some synthesizers).
  452. If no value is given, the pitch bend is returned to "no change".
  453. """
  454. if not (0 <= channel <= 15):
  455. raise ValueError("Channel not between 0 and 15.")
  456. if not (-8192 <= value <= 8191):
  457. raise ValueError("Pitch bend value must be between "
  458. "-8192 and +8191, not %d." % value)
  459. # "The 14 bit value of the pitch bend is defined so that a value of
  460. # 0x2000 is the center corresponding to the normal pitch of the note
  461. # (no pitch change)." so value=0 should send 0x2000
  462. value = value + 0x2000
  463. LSB = value & 0x7f # keep least 7 bits
  464. MSB = value >> 7
  465. self.write_short(0xe0 + channel, LSB, MSB)
  466. """
  467. MIDI commands
  468. 0x80 Note Off (note_off)
  469. 0x90 Note On (note_on)
  470. 0xA0 Aftertouch
  471. 0xB0 Continuous controller
  472. 0xC0 Patch change (set_instrument?)
  473. 0xD0 Channel Pressure
  474. 0xE0 Pitch bend
  475. 0xF0 (non-musical commands)
  476. """
  477. def time():
  478. """returns the current time in ms of the PortMidi timer
  479. pygame.midi.time(): return time
  480. The time is reset to 0, when the module is inited.
  481. """
  482. return _pypm.Time()
  483. def midis2events(midis, device_id):
  484. """converts midi events to pygame events
  485. pygame.midi.midis2events(midis, device_id): return [Event, ...]
  486. Takes a sequence of midi events and returns list of pygame events.
  487. """
  488. evs = []
  489. for midi in midis:
  490. ((status,data1,data2,data3),timestamp) = midi
  491. e = pygame.event.Event(MIDIIN,
  492. status=status,
  493. data1=data1,
  494. data2=data2,
  495. data3=data3,
  496. timestamp=timestamp,
  497. vice_id = device_id)
  498. evs.append( e )
  499. return evs
  500. class MidiException(Exception):
  501. """exception that pygame.midi functions and classes can raise
  502. MidiException(errno)
  503. """
  504. def __init__(self, value):
  505. self.parameter = value
  506. def __str__(self):
  507. return repr(self.parameter)
  508. def frequency_to_midi(freqency):
  509. """ converts a frequency into a MIDI note.
  510. Rounds to the closest midi note.
  511. ::Examples::
  512. >>> frequency_to_midi(27.5)
  513. 21
  514. >>> frequency_to_midi(36.7)
  515. 26
  516. >>> frequency_to_midi(4186.0)
  517. 108
  518. """
  519. return int(
  520. round(
  521. 69 + (
  522. 12 * math.log(freqency / 440.0)
  523. ) / math.log(2)
  524. )
  525. )
  526. def midi_to_frequency(midi_note):
  527. """ Converts a midi note to a frequency.
  528. ::Examples::
  529. >>> midi_to_frequency(21)
  530. 27.5
  531. >>> midi_to_frequency(26)
  532. 36.7
  533. >>> midi_to_frequency(108)
  534. 4186.0
  535. """
  536. return round(440.0 * 2 ** ((midi_note - 69) * (1./12.)), 1)
  537. def midi_to_ansi_note(midi_note):
  538. """ returns the Ansi Note name for a midi number.
  539. ::Examples::
  540. >>> midi_to_ansi_note(21)
  541. 'A0'
  542. >>> midi_to_ansi_note(102)
  543. 'F#7'
  544. >>> midi_to_ansi_note(108)
  545. 'C8'
  546. """
  547. notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
  548. num_notes = 12
  549. note_name = notes[int(((midi_note - 21) % num_notes))]
  550. note_number = int(round(((midi_note - 21) / 11.0)))
  551. return '%s%s' % (note_name, note_number)