Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing drum sounds in Python Music21 library

It's been a couple of weeks since I started reading the book "Making music with computers: creative programming in Python" and now i'm stucked while trying to play drum sounds with this library. I'm using Mit's music21 library, as the one proposed by the book didn't work for me (it's called simply "music"). This is a code example the book uses to play bass drum sound:

from music import *
drumPart = Part("Drums", 0, 9)
note = Note(ACOUSTIC_BASS_DRUM, QN) # a bass drum strike
drumPhrase = Phrase()
drumPhrase.addNote(note)
drumPart.addPhrase(drumPhrase)
Play.midi(drumPart)

I tried to do the same in music21 with a Hi Hat sound but no sound is played:

import music21
from music21 import note, stream, pitch, duration, instrument, tempo, chord
from music21.note import Note, Rest
from music21.chord import Chord
from music21 import midi

def createInstrument(instrument, midiChannel):
    i = instrument
    i.midiChannel = midiChannel
    return i

n = Note("A2", type='quarter')

drumPart = stream.Part()
drumPart.insert(createInstrument(instrument.HiHatCymbal(), 9))

drumMeasure = stream.Measure()
drumMeasure.append(n)
drumPart.append(drumMeasure)
drumPart.show('midi')

Any advice would be really helpful, as there is practically no information on the web about this library except its webPage.

Thanks in advance, Julián!

like image 744
Julian Avatar asked Nov 08 '22 10:11

Julian


1 Answers

Hi Julian I made it work on my Mac with a minor change. I hope that would help! I basically changed only one line of your code and now it works on my Mac. When I say it works I mean it is creating the mid file correctly but fail to open it.

The reason it fails to open it is that the default player (QuickTime in my case) was unable to run the mid file. You can install MuseScore (which is free) and set it as the default program for mid files then everything should work smoothly.

from music21 import stream, instrument
from music21.note import Note

n = Note("A2", type='quarter')

drumPart = stream.Part()
drumPart.insert(0, instrument.Woodblock())

drumMeasure = stream.Measure()
drumMeasure.append(n)
drumPart.append(drumMeasure)

# This line actually generate the midi on my mac but there is no relevant software to read it and the opening fail
drumPart.show('midi')
like image 141
Almog Cohen Avatar answered Nov 14 '22 21:11

Almog Cohen