Tuesday, October 15, 2024
STEM

Music Playback from a CSV (Python)

In my earlier blog post An Interactive Musical Keyboard Player (Python), I shared the full code on how to write an interactive musical keyboard that can also save what you play into memory and optionally to a file. In this post, I’ll share a related component as a separate code module that can read a previously saved file and playback all the notes in it along with specified duration for each note.

Using the application from the keyboard player (see the post link above), I played and saved some notes. The saved file (CSV) had the frequency of notes played in Hertz and duration in seconds. Although that version cannot capture the duration of a note (i.e. is it a quick press or a long press of the key on keyboard due to traditional computer’s keyboard limitation), this version of the application can indeed handle specific duration per note during playback. Therefore, we can edit the previously saved file and modify just the duration values as needed. This code expects the file to be in a subdirectory of the execution folder called ‘dataset’, but you can change it to whatever location by changing the path in the open() function. The file may look like this and is called notes.csv which is comma-separated and can be edited in Notepad or Excel or Google Sheets as long as it is saved back in the same CSV format as a text (UTF-8) file.

freqency,duration
220.00,0.25
233.08,0.25
246.96,0.50
261.60,0.25
277.20,0.25
293.68,1.0
311.12,0.85
220.00,0.25
233.08,0.25
246.96,0.50
293.68,1.0
293.68,1.0
349.2,0.25
415.28,0.25
349.2,0.25
392.0,0.25
415.28,0.25
523.2,0.25
493.92,1.0
523.2,0.985
220.00,0.25
233.08,0.25
246.96,0.50
261.60,0.25
277.20,0.25
293.68,1.0
311.12,0.85

Notice how some of the duration values are different in some lines. Shorter value means the note is played for a shorter period and longer value means the note is sustained for that many seconds before playing the next note.

Note that in order to run it, you’ll need to download or copy the source code and run it locally on your Python environment as the application requires access to your machine’s sound device (you cannot run it from here or remotely).

The Source Code:

A few things worth noting or explaining are noted in the source code. e.g.

# we have a row header
next(reader)
# Convert the data to a list of tuples
data = [(float(frequency), float(duration)) for frequency, duration in reader]
# Convert the frequency to a midi note number
note = int(69 + 12 * math.log(frequency / 440, 2))

I hope this was educational as well as interesting. I can attest it was quite fun for me creating this. Be sure to check out the complementary app in Related Posts section below. Enjoy!


Related Posts:

Leave a Reply

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

Back To Top
+