Merge pull request #1 from atsampson/master
[calfbox.git] / song_api_example.py
blobf4d232c2bde16e8b6c57212721f734f0cdcde843
1 import os
2 import sys
3 import struct
4 import time
5 import unittest
7 sys.path = ["./py"] + sys.path
9 import cbox
11 global Document
12 global Transport
13 Document = cbox.Document
14 Transport = cbox.Transport
16 song = Document.get_song()
18 # Delete all the tracks and patterns
19 song.clear()
21 # Add the first track
22 trk = song.add_track()
24 # Create a binary blob that contains the MIDI events
25 pblob = bytes()
26 for noteindex in range(20):
27 # note on
28 pblob += cbox.Pattern.serialize_event(noteindex * 24, 0x90, 36+noteindex*3, 127)
29 # note off
30 pblob += cbox.Pattern.serialize_event(noteindex * 24 + 23, 0x90, 36+noteindex*3, 0)
32 # This will be the length of the pattern (in pulses). It should be large enough
33 # to fit all the events
34 pattern_len = 10 * 24 * 2
36 # Create a new pattern object using events from the blob
37 pattern = song.pattern_from_blob(pblob, pattern_len)
39 # Add an instance (clip) of the pattern to the track at position 0
40 # The clip will contain the whole pattern (it is also possible to insert
41 # a single slice of the pattern)
42 clip = trk.add_clip(0, 0, pattern_len, pattern)
44 # Stop the song at the end
45 song.set_loop(pattern_len, pattern_len)
47 # Set tempo - the argument must be a float
48 Transport.set_tempo(160.0)
50 # Send the updated song data to the realtime thread
51 song.update_playback()
53 print ("Song length (seconds) is %f" % (cbox.Transport.ppqn_to_samples(pattern_len) * 1.0 / Transport.status().sample_rate))
55 # The /master object API doesn't have any nice Python wrapper yet, so accessing
56 # it is a bit ugly, still - it works
58 # Start playback
59 Transport.play()
60 print ("Playing")
62 while True:
63 # Get transport information - current position (samples and pulses), current tempo etc.
64 master = Transport.status()
65 print (master.pos_ppqn)
66 # Query JACK ports, new USB devices etc.
67 cbox.call_on_idle()
68 time.sleep(0.1)