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 prebuilt version available for Raspberry pi. This tutorial is not going 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.

rpi

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))
    sleep(0.1)

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  first.py

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

Thats it, Now start playing with Sonic PI.
Alsamixer

 

Leave a Reply

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