Jul 27, 2012

Playing Pi (or any number) with PiPlayer

A few weeks ago, I saw a great video by Numberphile on YouTube, and it got me thinking - I can do something like this. So, the next morning, I started up a Git repository and got to it. First thing to do was creating constant tones, which led me on quite a journey by itself.

Here’s the link to the GitHub repository: https://github.com/kroq-gar78/piplayer

How to run PiPlayer

Obtain the source:

git clone git://github.com/kroq-gar78/piplayer.git

Compile and run the program: ./run.sh (Linux) OR run (Windows)

This will play the digits of π at some length per tone (I keep changing it) and some type of sound wave (I keep changing that, too :P).

In the source, I’ve added 1 million digits of each \(\pi\)\(\tau\) (\(= 2\pi\)), and Euler’s constant \(e\). To change the constant being played, go to the line that says

BufferedReader pin = new BufferedReader( new FileReader("pi_1mil.txt") );

and change pi_1mil.txt to tau_1mil.txt or e_1mil.txt. If you have another constant of any number of digits (irrational ones sound the best, in my opinion), simply change pi_1mil.txt to the file that contains the digits of the new constant.

The result

What may be a surprise is that what comes out of the program is a rather nice tune, even though it really doesn’t have a melody. This isn’t just coincidence, however; there is a reason why it sounds so nice. What I’m doing by mapping each of the notes to a different note (in this example, using the key of C major) is forcing it to sound good. Any random set of notes assigned to a key will almost always sound “melodious”. So, our problem is now that we’re not really playing pi, but we’re faking it. In the next section, I attempt to solve this problem.

Base 12

To solve the aforementioned problem, I’ve created a program that calculates the digits of Pi and then converts them into base 12. In Western Classical music, there are 12 half-steps (semitones) per octave. By assigning each digit (0 through B in base 12) to a note in a single octave, we can try to create the “true” sound of pi (remember, math is just what we humans perceive as nature, so there is no “true” sound of pi, per se).

In one of the latest commits in the base12 branch, I have added a program called PiCalculator, which first calculates the digits of Pi, and then it converts them into base 12. For use in PiPlayer, the output must be piped into a file, and then PiPlayer must be edited to have the correct file path.

This command can be used to pipe the output of PiCalculator into a file:

java PiCalculator 200 | head -1 > pi_200_b12.txt

Notice that the output is piped into head to get just the first line, since the second line of the output is the execution time. Note that currently, it occasionally exits with an ArithmeticException error about dividing by zero, but it doesn’t affect the results and can be ignored.