Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

12.14. Representing Data as MIDI Music

Problem

You want to represent a series of data points as a musical piece, or just create music algorithmically.

Solution

Jim Menard's midilib library makes it easy to generate MIDI music files from Ruby. It's available as the midilib gem.

Here's a simple method for visualizing a list of numbers as a piano piece. The largest number in the list is mapped to the highest note on the piano keyboard (MIDI note 108), and the smallest number to the lowest note (MIDI note 21).

	require 'rubygems'
	require 'midilib'                                        # => false

	class Array
	  def to_midi(file, note_length='eighth')

	    midi_max = 108.0
	    midi_min = 21.0

	    low, high = min, max
	    song = MIDI::Sequence.new

	    # Create a new track to hold the melody, running at 120 beats per minute.
	    song.tracks << (melody = MIDI::Track.new(song))
	    melody.events << 
MIDI::Tempo.new(MIDI::Tempo.bpm_to_mpq(120))

	    # Tell channel zero to use the "piano" sound.
	    melody.events << MIDI::ProgramChange.new(0, 0)

	    # Create a series of note events that play on channel zero.
	    each do |number|
	      midi_note = (midi_min + ((number-midi_min) * (midi_max-low)/high)).to_i
	      melody.events << MIDI::NoteOnEvent.new(0, midi_note, 127, 0)
	      melody.events << MIDI::NoteOffEvent.new(0, midi_note, 127,
	                                              song.note_to_delta(note_length))
	    end

	    open(file, 'w') { |f| song.write(f) }
	  end
	end

Now you can get an audible representation of any list of numbers:

	((1..100).collect { |x| x ** 2 }).to_midi('squares.mid')

Discussion

The midilib library provides a set of classes for modeling ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required