[Tutor] Python Question

eryksun eryksun at gmail.com
Wed Jan 9 13:41:59 CET 2013


On Mon, Jan 7, 2013 at 6:31 PM, Dylan Kaufman <ketchup.candy at gmail.com> wrote:
>
> from winsound import Beep
>
> Beep(196, 1500)#G

winsound.Beep wraps the Windows (win32) system call of the same name.
Instead, consider using a cross-platform library such as PortAudio or
PortMidi:

http://sourceforge.net/apps/trac/portmedia

One option is to synthesize PCM audio and play it with PyAudio, which
wraps PortAudio. But you'll probably have more fun with MIDI (Musical
Instrument Digital Interface).

Installing pyPortMidi involves compiling libportmidi and the
Cython/Pyrex extension module. If you run into trouble there,
hopefully an OS X user on the list can help.

Alternatively, pygame includes pyPortMidi as pygame.midi:

pygame installers:
http://www.pygame.org/download.shtml

Demo:

import and initialize:

    >>> from time import sleep
    >>> from pygame import midi
    >>> midi.init()

list devices:

    >>> for i in range(midi.get_count()):
    ...   print i, midi.get_device_info(i)
    ...
    0 ('ALSA', 'Midi Through Port-0', 0, 1, 0)
    1 ('ALSA', 'Midi Through Port-0', 1, 0, 0)
    2 ('ALSA', 'TiMidity port 0', 0, 1, 0)
    3 ('ALSA', 'TiMidity port 1', 0, 1, 0)
    4 ('ALSA', 'TiMidity port 2', 0, 1, 0)
    5 ('ALSA', 'TiMidity port 3', 0, 1, 0)

open output for MIDI device 2:

    >>> device = 2
    >>> latency = 0
    >>> out = midi.Output(device, latency)

set the channel 0 instrument to GM (General MIDI) steel drum:

    >>> instrument = STEEL_DRUM = 114
    >>> channel = 0
    >>> out.set_instrument(instrument, channel)

play some notes:

    >>> MAX_VOL = 127
    >>> MID_C = 60
    >>> for i in range(12):
    ...   out.note_on(MID_C + i, MAX_VOL, channel)
    ...   sleep(0.5)
    ...   out.note_off(MID_C + i, MAX_VOL, channel)

You can also write MIDI messages directly (0x90 + n is "note on" for channel n):

    >>> out.write_short(0x90 + channel, MID_C, MAX_VOL)


General Links

MIDI and Music Synthesis
http://www.midi.org/aboutmidi/tut_midimusicsynth.php

Message Protocol
http://www.midi.org/techspecs/midimessages.php

GM Sound Set
http://www.midi.org/techspecs/gm1sound.php

Note Numbers:
http://www.midimountain.com/midi/midi_note_numbers.html


More information about the Tutor mailing list