Play music with Python and Sonic Pi

I recently found this application sonic pi using which you can create music. Sonic Pi is a live coding music synthesizer. It has a pre-built version available for Raspberry Pi. This tutorial is not going to cover the basics of how to use Sonic Pi, instead about how to use python along with Sonic Pi. In specific how to install the software and get the python api working.






You need to have a Raspberry Pi running Rasbian Jessie. Now update the package manager archive and install lxde if you have not installed it previously. This is required for Sonic Pi, since it is a GUI application.

$ sudo apt-get update
$ sudo apt-get install lxde

Now you install the Sonic PI,

$ sudo apt-get install sonic-pi

If you are using RPi display directly  then run the Sonic pi,

$ sonic-pi

or if you are using SSH connection from Linux  machine .

$ ssh -X pi@RPI-IPAddress 
$ sonic-pi

For python I used virtualenv

$ sudo apt-get install python-virtualenv
$ virtualenv mylocalpy
$ source mylocalpy/bin/activate

At the moment the sonic-pi is only supported by python3. So you need to install python packages using pip3.

(mylocalpy)pi@raspberrypi:~ $pip3 install python-sonic

Now lets start writing our first python program to generate music.

from psonic import *
import random

for i in range(35):
    play(random.randrange(10, 500))

Before running this app, you need to start the sonic pi and let it run in the background. This is because our application will connect with the sonic pi engine which listen to a particular port.

$ sonic-pi

Now you can run the application using python3.

$ python3

In case you dont hear anything the make sure to check the following,
1. Did you connect speaker to your Rpi 3.5 Audio jack?
2. Did you wait for a considerable after you started sonic-pi?

If you still have the problem then check your volume as shown below.

$ alsamixer

That’s it, now start playing with Sonic PI.


2 thoughts on “Play music with Python and Sonic Pi

  • October 3, 2017 at 5:37 pm

    better than the official documentation as you have pip3… which actually works, thanks!

    • November 3, 2017 at 8:32 pm



Leave a Reply

Your email address will not be published. Required fields are marked *