Sunday, January 29, 2017

JFugue Jython Example 16. Use "Replacement Maps" to Create Carnatic Music

This is Example 16 from JFugue website (JFugue Examples) in Jython.



# JFugue 16. Use "Replacement Maps" to Create Carnatic Music

'''
JFugue's ReplacementMap capability lets you use your own symbols
in a music string. JFugue comes with a CarnaticReplacementMap
that maps Carnatic notes to microtone frequencies.
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

from org.jfugue.player import Player
from org.staccato.maps import CarnaticReplacementMap
from org.staccato import ReplacementMapPreprocessor

rmp = ReplacementMapPreprocessor.getInstance()
rmp.setReplacementMap(CarnaticReplacementMap())

player = Player()
player.play("<S> <R1> <R2> <R3> <R4>")

JFugue Jython Example 15. Anticipate Musical Events Before They Occur

This is Example 15 from JFugue website (JFugue Examples) in Jython.



# JFugue 15. Anticipate Musical Events Before They Occur

'''
You might imagine creating new types of ParserListeners,
like an AnimationParserListener, that depend on knowing
about the musical events before they happen. For example,
perhaps your animation is of a robot playing a drum or
strumming a guitar. Before the note makes a sound, the
animation needs to get its virtual hands in the right
place, so you might want a notice 500ms earlier that
a musical event is about to happen. To bend time with
JFugue, use a combination of the TemporalPLP class
and Player.delayPlay(). delayPlay() creates a new
thread that first waits the specified amount of
time before playing. If you do this, make sure to
call delayPlay() before plp.parse().
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

from org.jfugue.player import Player
from org.jfugue.temporal import TemporalPLP
from org.staccato import StaccatoParser
from org.jfugue.devtools import DiagnosticParserListener

MUSIC = "C D E F G A B"
TEMPORAL_DELAY = 500

# Part 1. Parse the original music
parser = StaccatoParser()
plp = TemporalPLP()
parser.addParserListener(plp)
parser.parse(MUSIC)

# Part 2. Send the events from Part 1,
# and play the original music with a delay
dpl = DiagnosticParserListener()
# Or your AnimationParserListener!
plp.addParserListener(dpl)
Player().delayPlay(TEMPORAL_DELAY, MUSIC)
plp.parse()

Saturday, January 28, 2017

JFugue Jython Example 14. Create interactive musical programs using the RealtimePlayer.

This is Example 14 from JFugue website (JFugue Examples) in Jython.



# JFugue 14. Play Music in Realtime

'''
Create interactive musical programs using the RealtimePlayer.
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

import random
from org.jfugue.pattern import Pattern
from org.jfugue.realtime import RealtimePlayer
from org.jfugue.theory import Note

player = RealtimePlayer()
quit = False

s = [None]*3
s[0]="Enter a '+C' to start a note,"
s[1]="'-C' to stop a note, 'i' for a random instrument,"
s[2]="'p' for a pattern, or 'q' to quit\n"
info = " ".join(s)

PATTERNS = [Pattern("Cmajq Dmajq Emajq"),
            Pattern("V0 Ei Gi Di Ci  V1 Gi Ci Fi Ei"),
            Pattern("V0 Cmajq V1 Gmajq")]

while quit == False:
    entry = raw_input(info)
    if entry.startswith("+"):
        player.startNote(Note(entry[1:]))
    elif entry.startswith("-"):
        player.stopNote(Note(entry[1:]))
    elif entry.lower()=="i":
        player.changeInstrument(random.randint(0,127))
    elif entry.lower()=="p":
        player.play(random.choice(PATTERNS))
    elif entry.lower()=="q":
        quit = True
        player.close()

JFugue Jython Example 13. Create a Listener to Find Out About Music

This is Example 13 from JFugue website (JFugue Examples) in Jython.



# JFugue 13. Create a Listener to Find Out About Music

'''
You can create a ParserListener to listen for any musical
event that any parser is parsing. Here, we'll create a
simple tool that counts how many "C" notes (of any octave)
are played in any song.
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

from java.io import File
from javax.sound.midi import MidiSystem
from org.jfugue.midi import MidiParser
from org.jfugue.parser import ParserListenerAdapter

class MyParserListener(ParserListenerAdapter):
    counter = 0
    def onNoteParsed(self,note):
        # A "C" note is in the 0th position of an octave
        if note.getPositionInOctave() == 0:
            self.counter+=1

parser = MidiParser()
listener = MyParserListener()
parser.addParserListener(listener)
parser.parse(MidiSystem.getSequence(File("RowYourBoat.mid")))
print "There are %d 'C' notes in this music." % listener.counter

Friday, January 27, 2017

JFugue Jython Example 12. Connecting Any Parser to Any ParserListener

This is Example 12 from JFugue website (JFugue Examples) in Jython.



# JFugue 12. Connecting Any Parser to Any ParserListener

'''
You can use JFugue to convert between music formats.
Most commonly, JFugue is used to turn Staccato music
into MIDI sound. Alternatively, you can play with the
MIDI, MusicXML, and LilyPond parsers and listeners.
Or, you can easily create your own parser or listener,
and it will instantly interoperate with the other
existing formats. (And if you convert to Staccato,
you can then play the Staccato music... and edit it!)
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

from java.io import File
from javax.sound.midi import MidiSystem
from org.jfugue.midi import MidiParser
from org.jfugue.player import Player
from org.staccato import StaccatoParserListener

parser = MidiParser()
listener = StaccatoParserListener()
parser.addParserListener(listener)
parser.parse(MidiSystem.getSequence(File("RowYourBoat.mid")))
staccatoPattern = listener.getPattern()

print staccatoPattern

player = Player()
player.play(staccatoPattern)

JFugue Jython Example 11. See the Contents of a MIDI File in Human-Readable and Machine-Parseable Staccato Format

This is Example 11 from JFugue website (JFugue Examples) in Jython.



# JFugue 11. See the Contents of a MIDI File in Human-Readable
# and Machine-Parseable Staccato Format

'''
Want to see the music in your MIDI file? Of course,
you could load it in a sheet music tool. Here's how you can load it
with JFugue. You'll get a Pattern of your music, which you can then
pick apart in interesting ways (for example, count how many "C" notes
there are... that's coming up in a few examples)
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

from java.io import File, FileNotFoundException
from org.jfugue.midi import MidiFileManager


try:
    pattern = MidiFileManager.loadPatternFromMidi(File("RowYourBoat.mid"))
except FileNotFoundException:
    print "file not found"
    pattern = None

pat = pattern.toString().split(" ")
for p in pat: print p

Thursday, January 26, 2017

JFugue Jython Example 10. All That, in One Line of Code?

This is Example 10 from JFugue website (JFugue Examples) in Jython.



# JFugue 10. All That, in One Line of Code?

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

'''
Try this. The main line of code even fits within
the 140-character limit of a tweet.
'''

from org.jfugue.player import Player
from org.jfugue.rhythm import Rhythm
from org.jfugue.theory import ChordProgression

cp = ChordProgression("I IV vi V").eachChordAs("$_i $_i Ri $_i")
r = Rhythm().addLayer("..X...X...X...XO")
Player().play(cp,r)

JFugue Jython Example 9. Advanced Rhythms

This is Example 9 from JFugue website (JFugue Examples) in Jython.



# JFugue 9. Advanced Rhythms

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

'''
Through the Rhythm API, you can specify a variety of alternate
layers that occur once or recur regularly. You can even create
your own "RhythmAltLayerProvider" if you'd like to create a
new behavior that does not already exist in the Rhythm API.
'''

from org.jfugue.player import Player
from org.jfugue.rhythm import Rhythm

r = Rhythm()
r = r.addLayer("O..oO...O..oOO..") # This is Layer 0
r = r.addLayer("..S...S...S...S.")
r = r.addLayer("````````````````")
r = r.addLayer("...............+") # This is Layer 3
# Replace Layer 3 with this string on the 4th (count from 0) measure
r = r.addOneTimeAltLayer(3, 3, "...+...+...+...+")
r = r.setLength(4) # Set the length of the rhythm to 4 measures
# Play 2 instances of the 4-measure-long rhythm
Player().play(r.getPattern().repeat(2))

Wednesday, January 25, 2017

JFugue Jython Example 8. Introduction to Rhythms

This is Example 8 from JFugue website (JFugue Examples) in Jython.



# JFugue 8. Introduction to Rhythms

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

'''
One of my favorite parts of the JFugue API is the ability
to create rhythms in a fun and easily understandable way.
The letters are mapped to percussive instrument sounds,
like "Acoustic Snare" and "Closed Hi Hat". JFugue comes
with a default "rhythm set", which is a Map
with entries like this: put('O', "[BASS_DRUM]i").
'''

from org.jfugue.player import Player
from org.jfugue.rhythm import Rhythm

def getRhythm():
    r = Rhythm()
    r = r.addLayer("O..oO...O..oOO..")
    r = r.addLayer("..S...S...S...S.")
    r = r.addLayer("````````````````")
    r = r.addLayer("...............+")
    return r
    

rhythm = getRhythm()
Player().play(rhythm.getPattern().repeat(2))

It is best to use simple variables, like r, in local scope, and longer and more descriptive variables in global namespace.


Tuesday, January 24, 2017

JFugue Jython Example 7. Twelve-Bar Blues in Two Lines of Code

This is Example 7 from JFugue website (JFugue Examples) in Jython.



# JFugue 7. Twelve-Bar Blues in Two Lines of Code


'''
Twelve-bar blues uses a I-IV-V chord progression.
But really, it's the Major 7ths that you'd like
to hear... and if you want to play each chord in
arpeggio, you need a 6th in there as well. But
creating a I7%6-IV7%6-V7%6 chord progression is
messy. So, this code creates a I-IV-V progression,
then distributes a 7%6 across each chord, then
creates the twelve bars, and then each chord is
played as an arpeggio with note dynamics (note on
velocity - how hard you hit the note). Finally,
the pattern is played with an Acoustic_Bass
instrument at 110 BPM. With all of the method
chaining, that is kinda done in one line of code.
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

from org.jfugue.player import Player
from org.jfugue.theory import ChordProgression

p1 = "$0 $0 $0 $0 $1 $1 $0 $0 $2 $1 $0 $0"
p2 = """
$0ia100 $1ia80 $2ia80 $3ia80
$4ia100 $3ia80 $2ia80 $1ia80"""
pattern = ChordProgression("I IV V")
pattern = pattern.distribute("7%6")
pattern = pattern.allChordsAs(p1)
pattern = pattern.eachChordAs(p2)
pattern = pattern.getPattern()
pattern = pattern.setInstrument("Acoustic_Bass")
pattern = pattern.setTempo(100)
Player().play(pattern)

In Jython and Python, it is important to write code that can fit in one line. It is possible to write a very long line in a editor, but that is hardly clean code, which is the advantage of Python. Usually, you will use functions or classes, which will define a global variable like pattern, and inside the function use p or something simple. In Python it is very important to use simple names whenever possible so you do not accidentally create new variables.


JFugue Jython Example 6. Advanced Chord Progressions

This is Example 6 from JFugue website (JFugue Examples) in Jython.



# JFugue 6. Advanced Chord Progressions

'''
You can do some pretty cool things with chord
progressions. The methods below use $ to indicate
an index into either the chord progression (in
which case, the index points to the nth chord),
or a specific chord (in which case the index
points to the nth note of the chord). Underscore
means "the whole thing". If you change the indexes,
make sure you don't introduce an
ArrayOutOfBoundsException (for example, a major
chord has only three notes, so trying to get the
4th index, $3 (remember that this is zero-based),
would cause an error).
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

from org.jfugue.player import Player
from org.jfugue.theory import ChordProgression

cp = ChordProgression("I IV V")
player = Player()
p1 = "$0q $1q $2q Rq"
p2 = "$0q $0q $0q $0q $1q $1q $2q $0q"
p3a = "$0 $0 $0 $0 $1 $1 $2 $0"
p3b = "V0 $0s $1s $2s Rs V1 $_q"
player.play(cp.eachChordAs(p1))
player.play(cp.allChordsAs(p2))
player.play(cp.allChordsAs(p3a).eachChordAs(p3b))

JFugue Jython Example 5. Introduction to Chord Progressions

This is Example 5 from JFugue website (JFugue Examples) in Jython.



# JFugue 5. Introduction to Chord Progressions

from __future__ import print_function
import sys
sys.path.append("C:/jfugue-5.0.7.jar")

'''
It's easy to create a Chord Progression in JFugue.
You can then play it, or you can see the notes that
comprise the any of the chords in the progression.
'''

from org.jfugue.player import Player
from org.jfugue.theory import ChordProgression

cp = ChordProgression("I IV V")
chords = cp.setKey("C").getChords()
for chord in chords:
    print("Chord %s has these notes: " % chord)
    notes = chord.getNotes()
    for note in notes:
        print("%s " % note,end = "\t")
    print("")

player = Player()
player.play(cp)

For each of the 3 chords, the 3 notes are shown, with tabs, in between. For the notes, the end parameter is changed from default newline, to tab character.


JFugue Jython Example 4. Introduction to Patterns, Part 2

This is Example 4 from JFugue website (JFugue Examples) in Jython.



# JFugue 4. Introduction to Patterns, Part 2

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

'''
Voice and instruments for a pattern can also be set through the API.
In JFugue, methods that would normally return 'void' instead return
the object itself, which allows you do chain commands together, as seen
in this example.
'''

from org.jfugue.player import Player
from org.jfugue.pattern import Pattern

p1 = Pattern("Eq Ch. | Eq Ch. | Dq Eq Dq Cq").setVoice(0)
p1 = p1.setInstrument("Piano")
p2 = Pattern("Rw     | Rw     | GmajQQQ  CmajQ").setVoice(1)
p2 = p2.setInstrument("Flute")
player = Player()
player.play(p1, p2)

Sunday, January 22, 2017

JFugue Jython Example 3. Introduction to Patterns

This is Example 3 from JFugue website (JFugue Examples) in Jython.



# JFugue 3. Introduction to Patterns

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

'''
Patterns are one of the fundamental units of music in JFugue.
They can be manipulated in musically interesting ways.
'''

from org.jfugue.player import Player
from org.jfugue.pattern import Pattern

p1 = Pattern("V0 I[Piano] Eq Ch. | Eq Ch. | Dq Eq Dq Cq")
p2 = Pattern("V1 I[Flute] Rw     | Rw     | GmajQQQ  CmajQ")
player = Player()
player.play(p1, p2)
    

JFugue Jython Example 2. Playing multiple voices, multiple instruments, rests, chords, and durations

This is Example 2 from JFugue website (JFugue Examples) in Jython.



# JFugue 2. Playing multiple voices, multiple instruments,
# rests, chords, and durations

'''
This example uses the Staccato 'V' command for specifing voices,
'I' for specifying instruments (text within brackets is looked
up in a dictionary and maps to MIDI instrument numbers), '|' (pipe)
for indicating measures (optional), durations including 'q' for
quarter duration, 'qqq' for three quarter notes (multiple durations
can be listed together), and 'h' for half, 'w' for whole, and '.'
for a dotted duration; 'R' for rest, and the chords G-Major and
C-Major. Whitespace is not significant and can be used for visually
pleasing or helpful spacing.
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

from org.jfugue.player import Player

player = Player()
v = [None]*2
v[0] = "V0 I[Piano] Eq Ch. | Eq Ch. | Dq Eq Dq Cq"
v[1] = "V1 I[Flute] Rw | Rw | GmajQQQ CmajQ"
strPlay = " ".join(v)
player.play(strPlay)

JFugue Jython Example 1. "Hello, World" in JFugue

The JFugue website has 18 examples (JFugue Examples).


The examples are in Java. This is Jython for Example 1. This assumes jar file is in C: drive.


# JFugue Example 1. "Hello, World" in JFugue

'''
Create music with only a few lines of code!
'''

import sys
sys.path.append("C:/jfugue-5.0.7.jar")

from org.jfugue.player import Player

player = Player()
player.play("C D E F G A B")