r/supriya_python • • Feb 07 '25

An arpeggiator in Supriya

4 Upvotes

Introductory remarks

For the first example, I wanted something simple, but interesting. I also wanted something that could be built upon to demonstrate more of Supriya's features in the future. After some thought, I decided a arpeggiator would work nicely.

Before I talk about the code, I should mention that I develop on Linux. I don't own a Macintosh or any computers running Windows. So I won't be able to help with any OS-specific problems (outside of Linux). If you are a Linux user then you might need to export the following environmental variables:

export SC_JACK_DEFAULT_INPUTS="system"
export SC_JACK_DEFAULT_OUTPUTS="system"

I put them in my .bashrc file. I needed to do this to get Jack to connect with the SuperCollider server's audio ins and outs.

You will need to install both Supriya and SuperCollider. Installing Supriya is simple, as it's in PyPi. Installing SuperCollider isn't difficult, but the installation details vary by OS. See Supriya's Quickstart guide for more info. I also used click for handling command line arguments. So install that inside your virtual environment:

pip install click

The code

I previously had the script here, but things kept getting deleted somehow. The script was rather long, and maybe Reddit wasn't built to handle that much gracefully. So I'll just leave a link to the code in GitHub: arpeggiator.py.

I split the code into two sections: one has all the general Python code, and the other has the Supriya code. I did this to make it obvious how little Supriya code is needed to make this work. Within each section, the function are organized alphabetically. Hopefully that should make it easy to find the function you want to look at.

To run the script, name it whatever you want, and call it like this:

python my_script.py --chord C#m3 --direction up

You can also call it with shortened argument names:

python my_script.py -c C#m3 -d up

The chord argument should be written like this:

<Chord><(optional) accidental><key><octave>

For example, DM3 would be a D major chord in the third octave. Or C#m5 would be a C-sharp minor chord in the fifth octave.

chord and direction default to CM4 and up, respectively, if they are not provided. I limited the octaves to the range 0-8. So if you try passing anything less than 0 or greater than 8 as an octave, the script will exit with an error. direction has three options: up, down, up-and-down, in the same way many synthesizers do. The chords played are all 7th chords, meaning the root, third, fifth, and seventh notes are played for each chord. I just thought it sounded better than way.

Given the above arguments, the script will play an arpeggio of a C-sharp minor 7th chord in octave 3. The synth playing the notes is using a saw-tooth waveform. Each channel has its own note, and I slightly detuned them to make it sound a bit fuller. The arpeggio will continue playing until the program is stopped.

A warning about volume

I included this warning as a comment in the SynthDef function, but I want to mention it here again. When using SuperCollider, it is very easy to end up with a volume that is loud enough to damage ears or potentially speakers. I've placed a limiter in the SynthDef to stop this from happening, but as anyone can change the code, I thought I should write another warning. There's a good chance that the current setting in the limiter is so low that you won't hear anything. So my advice is to TAKE OFF your headphones, if you're using them, and SLOWLY increase the Limiter's level argument. DO NOT set it above 1. If the audio is still too quiet, then SLOWLY start turning up the amplitude argument. DO NOT set amplitude above 1, either. It shouldn't be necessary. YOU'VE BEEN WARNED! I take no responsibility for any damage done to one's hearing or audio equipment if my advice is ignored.

Just to be clear, I talking about this code:

# Be VERY CAREFUL when changing amplitude!
def saw(frequency=440.0, amplitude=0.5, gate=1) -> None:
    signal = LFSaw.ar(frequency=[frequency, frequency - 2])
    signal *= amplitude
    # Be VERY CAREFUL with changing level!
    signal = Limiter.ar(duration=0.01, level=0.1, source=signal)
    
    adsr = Envelope.adsr()
    env = EnvGen.kr(envelope=adsr, gate=gate, done_action=2)
    signal *= env

    Out.ar(bus=0, source=signal)

Final thoughts

There is a much simpler way to implement this, honestly. If the script accepted a MIDI note as the starting note, rather than a string indicating a chord, accidental, a key, and an octave, then a lot of this code would go away. But I wanted to try taking something more musical as the input.


r/supriya_python • • Feb 06 '25

What is Supriya?

8 Upvotes

Supriya is a Python API for SuperCollider. If you're unfamiliar with SuperCollider, it's described on its website as:

A platform for audio synthesis and algorithmic composition, used by musicians, artists and researchers working with sound.

A slightly more in-depth explanation of SuperCollider, taken from the documentation here, says:

The name "SuperCollider" is in fact used to indicate five different things:
* an audio server

* an audio programming language

* an interpreter for the language, i.e. a program able to interpret it

* the interpreter program as a client for the server

* the application including the two programs and providing mentioned functionalities

SuperCollider is very cool. I'm assuming that people reading this already have some familiarity with it, and I will only be talking about the parts of SuperCollider that are relevant to using Supriya. If you want to know more about SuperCollider as a whole, check out the website, the extensive documentation, or the dedicated SuperCollider community found here r/supercollider.

So if SuperCollider is so cool, and offers so much, why do we need Supriya? The answer to this is very subjective, of course, but here are my reasons:

  1. I didn't care for sclang (the audio programming language referred to above)

  2. I love Python, and wanted to not only be able to use it in my project, but have access to the massive Python ecosystem

  3. I personally felt that sclang was ill-suited to my project (I'll be talking about my project more in future posts)

  4. The license tied to sclang allows for its use in commercial projects, but requires releasing that project's code as open source (Supriya's license doesn't require that, and it is implemented in a way that frees it from SuperCollider's license)

One thing that should be mentioned at this point is the design philosophy of Joséphine Wolf Oberholtzer, Supriya's creator (I copied this from a GitHub discussion we had when I first started learning Supriya):

The answer to the broader question is that no, supriya does not attempt to re-implement everything implemented in sclang. I try to keep supriya more narrowly scoped to server management, OSC, synthdefs, and timing-related concerns (clocks, basic patterns, etc.).

Supriya is intended as a foundational layer that other projects can be built on. I'm not currently planning on implementing (for example) an IDE, UI bindings, any of the graphical stuff from sclang, any of the micro-language / DSL stuff for live coding, etc. I think most of those topics either don't have obvious single solutions, will see limited use, or will generally be a maintenance burden on me.

I am hoping to implement code for modeling simple DAW logic: mixers, channels/tracks, sends/receives, monitoring, etc.

So Supriya was never meant to be a one-to-one port of the SuperCollider client, sclang, its interpreter, etc., to Python. It's a Python API for the SuperCollider server scsynth. The focus of the API isn't live coding, although it would be interesting to see someone try that with something like a Jupyter notebook.

Anyone already familiar with sclang will recognize most things in Supriya. The learning curve isn't very steep. However, as a relatively young project being maintained by one person, the documentation is still rather basic. There are also some things that are just different enough to be a bit confusing for someone coming from sclang. My purpose in creating this community was to have a place for people interested in Supriya to ask questions, share music or projects they've made with Supriya, and learn. I'm hoping we can create a knowledge base that will help others discover and use this awesome API.

Lastly, I should mention that I'm not an expert in either SuperCollider or Supriya. I'm willing to share and help out, but will definitely get things wrong from time to time, or be unable to answer some questions! Joséphine has been very helpful when I've asked questions on the Discussion page of Supriya's GitHub repo . She is the expert, so she is the best source of information. I'm simply hoping to help more widely spread knowledge and awareness via this community.


r/supriya_python • • Feb 15 '25

Signal routing, effects, and MIDI Control Change messages

2 Upvotes

Introduction

This new demo builds on the previous script by adding effects and handling MIDI Control Change messages. Introducing effects requires talking about signal routing in Supriya/SuperCollider, specifically buses, groups, and order of execution on the SuperCollider server. So most of this post will be dedicated to that. Handling MIDI Control Change messages is actually very easy, and won't really require much explanation.

The code

As usual, the code can be found in the supriya_demos GitHub repo. Since there are now three SynthDefs (two for the effects plus one for the saw synth), I split those out into their own module. The code for that module and the main script can be found here.

Signal routing

SuperCollider comes with a few different kinds of effects UGens out of the box. I only included two (delay and reverb) in this demo, as I felt that was enough to show how to use effects and handle signal routing. The SynthDef for an effects UGen isn't very different than a SynthDef for a sound-producing UGen, like the saw SynthDef that was used in both this demo and the previous one. One important difference is that the effects UGens' SynthDefs have an In UGen to intercept the audio output of another UGen. This is how we apply the delay and reverb to the saw synth. We also need to change the source of the Out UGen in a few places. The Out UGen is how we direct the audio output. The In and Out UGens actually get the audio signal from a bus, so we need to create new buses and pass those to the In and Out UGens.

An in-depth discussion of signal routing and buses in SuperCollider is beyond the scope of this post. Anyone interested in digging into the details of the architecture should watch one of Eli Fieldsteel's videos on the topic. I'll only be briefly covering to topic here.

Looking at some code from the demo script, you can see the buses being created and passed to the SynthDef when the Synth instance is created:

delay_bus = server.add_bus(calculation_rate='audio')
reverb_bus = server.add_bus(calculation_rate='audio')

delay_synth = effects_group.add_synth(
    synthdef=delay,
    in_bus=delay_bus, <- HERE
    maximum_delay_time=0.2, 
    delay_time=0.2, 
    decay_time=5.0,
    out_bus=reverb_bus <- HERE
)

reverb_synth = effects_group.add_synth(
    synthdef=reverb,
    in_bus=reverb_bus, <- HERE
    mix=0.33,
    room_size=1.0,
    damping=0.5,
    out_bus=0, <- DEFAULT
)

...

if message.type == 'note_on':
        frequency = midi_note_number_to_frequency(midi_note_number=message.note)
        synth = synth_group.add_synth(
                synthdef=saw, 
                frequency=frequency, 
                out_bus=delay_bus <- HERE
)

Visually, the code above has done this:

One point worth mentioning is that the effects synths are long-lived, unlike the saw synth. So the delay and reverb synths are created once and persist throughout the life of the program, whereas the saw synths are created and freed on a per note basis.

Creating and assigning audio buses is just one part of routing the signal, though. In addition to assigning the buses to the UGens, you need to make that the order of execution of synths on the server is correct. SuperCollider has this article on order of execution, and Eli Fieldsteel's video that I linked above also has a great explanation. Suffice it to say that sound-producing synths need to come before the sound-consuming ones on the server. This is generally done via the add_action argument that methods like add_synth and add_group accept. The easiest way to make sure that the synths' order of execution is correct is to create groups, assign all of the sound-producing synths to one group and the sound-consuming synths to another. Then all you need to do is make sure that the sound-consuming synths' group comes after the sound-producing one. That's kind of a mouthful, but in code it's very easy to do. Create the groups like this:

synth_group = server.add_group()
effects_group = server.add_group(add_action=AddAction.ADD_AFTER)

then add the synths to them like shown above.

If you don't get the order correct, then you won't hear any sound when playing the synths. This can also happen if you don't assign the buses correctly. The Out UGen of whatever synth is the final one in the audio processing chain has to point to the default audio out (unless you have a more sophisticated audio hardware setup). This can be specified by supplying 0 to the bus argument of Out's ar method.

Another benefit to using groups is that if you have multiple synths in the same group that all have the same parameter, like if you want to update the audio out bus of all of them, you can do that in one operation by calling synth_group.set(out_bus=new_bus), for example. Even if only a few of the synth's have an out_bus parameter, you can still call it on the group. The synths without that parameter will simply ignore the call.

MIDI Control Change messages

Handling MIDI Control Change messages is very straightforward. When you intercept the incoming MIDI messages, you just check the type of message, and then the control number. The control number is what maps the control change value to the parameter you want to change, like so:

if message.type == 'control_change':
    # Figure out which parameter should be changed based on the 
    # control number.
    if message.is_cc(DELAY_CC_NUM):
        scaled_decay_time = scale_float(value=message.value, target_min=0.0, target_max=10.0)
        effects_group.set(decay_time=scaled_decay_time)
        
    if message.is_cc(REVERB_CC_NUM):
        scaled_reverb_mix = scale_float(value=message.value, target_min=0.0, target_max=1.0)
        effects_group.set(mix=scaled_reverb_mix)

You can map any control number to any parameter. In the demo script I have control number 0 mapped to the decay time of the delay, and control number 1 mapped the the reverb's mix. If that won't work for you, you can simply change those values here:

DELAY_CC_NUM: int = 0
...
REVERB_CC_NUM: int = 1

The only other thing worth mentioning is that you have to scale the value of the MIDI Control Change message to an appropriate range. Most MIDI messages can only send values in the range 0-127, whereas in Supriya you might be dealing with parameters in a different range. For example, many UGen's parameters want a float in the range 0.0-1.0 rather than an integer.

Closing remarks

Everything I said in the previous post regarding ports still applies to this script. So the script will find and connect to all available MIDI input ports.


r/supriya_python • • Feb 15 '25

A Discord server

1 Upvotes

I created a Discord server for anyone interested:

https://discord.gg/W6CxnF7HxX


r/supriya_python • • Jun 21 '25

Wavetable synthesis

5 Upvotes

Introduction

There are a few different ways to do wavetable synthesis with Supriya, and a few different UGens that allow you to do it. This demo shows how to use the Osc (interpolating wavetable oscillator), COsc (chorusing wavetable oscillator), and VOsc (variable wavetable oscillator) UGens. It only recently became possible to use these UGens in Supriya because Josephine is amazing and added a few things to Supriya. So please make sure to show your appreciation by starring the Supriya GitHub repo!

The code

As usual, the code can be found in the supriya_demos GitHub repo. The script for this demo can be found here.

Wavetable synthesis

Eli Fieldsteel has 2 video tutorials on wavetable synthesis. The first is here. Both are great, and I recommend everyone to watch them. When watching them, you'll quickly realize that you won't be able to directly translate the sclang code to Supriya. This is because the sclang Wavetable and Signal classes do not exist in Supriya. This used to be somewhat of a problem because while the Signal class is mostly a wrapper around an array of floats, it also formats the data in a certain way. The various sineFill methods are also methods of the Signal class.

sineFill is available in Supriya, however the way you use it is as an argument to the Buffer class' generate method. So you need to create a buffer, and then call generate on it, like so:

buffer.generate(
    command_name='sine1',
    amplitudes=[some list of values],
    as_wavetable=True,
)

If you'd like to see where this function is defined in the repo, it's here. I meant to include an example of this, but ran out of time.

The other way that Eli creates wavetables in his videos is by starting with an envelope. One key feature that had been missing to make it possible to do this in Supriya was an equivalent of theasSignal method. Luckily, Josephine added a to_array method to the Envelope class that does the same thing. There was still one more step required to convert an Envelope into a wavetable, but I simply added that myself as a function in the demo script. It's called convert_to_wavetable in the script. The code in SuperCollider that converts a Signal to wavetable format is actually in C++. It isn't very complicated, but if someone wants to see the original code, I included a link to it in a comment in the script.

The basic steps to create an envelope and convert it to a wavetable are:

  1. Create a buffer. This needs to be double the size of the envelope after to_array has been called on it. to_array has a length argument that defaults to 1024. So when creating the buffer, you want frame_count=2048 , unless you set to_array's length to something else.

  2. Create an envelope. I wrote a function that creates an envelope with random values.

  3. Call to_array on the envelope.

  4. Convert the output of to_array to wavetable format.

  5. Zero out the buffer.

  6. Fill the buffer with the array that is now in wavetable format.

The Osc and COsc UGens take a buffer ID. So any SynthDef that includes those UGens will need to accept a buffer ID as an argument. The VOsc UGen works a bit differently. As Eli explains in this tutorials, that UGen allows you to transition between multiple wavetables. So VOsc needs the ID of the first buffer, as well as the number of buffers to use. In order to make this UGen work correctly, you need all of the buffers it uses to be sequential. The easiest way to do that is to use a BufferGroup in Supriya.

I used a lot of randomness and modulation in this demo. For example, I modulate the buffer_id and phase arguments of VOsc with LFNoise1:

signal = VOsc.ar(
        buffer_id=LFNoise1.ar(frequency=1).scale(
            input_minimum=-1.0,
            input_maximum=1.0,
            output_minimum=buf_start_num,
            output_maximum=num_buffs - 1,
        ), 
        frequency=frequency, 
        phase=LFNoise1.ar(frequency=0.3).scale(
            input_minimum=-1.0,
            input_maximum=1.0,
            output_minimum=-(8*pi),
            output_maximum=(8*pi),
        )
    )

I do the same with the initial_phase of Osc:

Osc.ar(
    buffer_id=buffer_id, 
    frequency=frequency, 
    initial_phase=LFNoise1.ar(frequency=1).scale(
        input_minimum=-1.0,
        input_maximum=1.0,
        output_minimum=-(8*pi),
        output_maximum=(8*pi),
    )
)

The envelopes are created with randomness, too:

num_segments = random.randrange(4, 20)
amplitudes = [random.uniform(-1.0, 1.0) for _ in range(num_segments + 1)]
durations = [random.randint(1, 20) for _ in range(num_segments)]
curves = [EnvelopeShape.WELCH for _ in range(num_segments)]

return Envelope(
    amplitudes=amplitudes,
    durations=durations,
    curves=curves,
)

I liked the sound of the Welch curves, though, so I didn't randomize those.

A side note

I've been wondering how to apply an envelope to a low-pass filter for a while. I finally got around to looking it up, and found a post on the SuperCollider forums where someone shows how they do it. This is the comment that shows how to do it. I used it in this demo. This is the code where that is done:

filter_envelope = EnvGen.kr(
        envelope=Envelope.adsr(
            attack_time=1.0,
            decay_time=0.5,
            sustain=0.5,
            release_time=0.3,
        ), 
    )

    # Apply the envelope to the cutoff frequency.
    signal = RLPF.ar(
        source=signal, 
        frequency=cutoff + filter_envelope.scale(
            input_minimum=0.0,
            input_maximum=1.0,
            output_minimum=0,
            output_maximum=800,
        ), 
        reciprocal_of_q=0.1,
    )

Final Thoughts

This will probably be the last demo for a while as I'm having a major surgery in a few days. The recovery will be long, and I probably won't be working on any demos during that time. I am thinking about trying to build a synth inspired by the Ensoniq ESQ 1, though. So I might be posting something about that in 4-6 weeks.