Introducing WaveFile

June 19, 2009

I have been playing around with building a simple synthesizer in Ruby. Needing a way to actually hear the generated sounds (a useful feature), I settled on having it save sounds to Wave format (*.wav). Not finding any existing Ruby libraries for reading/writing wave files, I made my own. The end result is a gem called WaveFile. The code is hosted on GitHub, while the gem is hosted at GitHub hosted at RubyGems.org.

How Do I Use This Thing?

First, install the WaveFile gem…

sudo gem install wavefile

…and include it in your Ruby program:

require 'wavefile'

To open a wave file and get the raw sample data:

w = WaveFile.open("myfile.wav")
samples = w.sample_data

You can also get the sample data in a normalized form, with each sample between -1.0 and 1.0:

normalized_samples = w.normalized_sample_data

You can get basic metadata:

w.num_channels      # 1 for mono, 2 for stereo
w.sample_rate       # 11025, 22050, 44100, etc.
w.bits_per_sample   # 8 or 16

To create and save a new wave file:

w = WaveFile.new(1, 44100, 16)  # num_channels,
                                # sample_rate,
                                # bits_per_sample
w.sample_data = <array of samples goes here>
w.save("myfile.wav")

When calling the sample_data=() method, the passed in array can contain either raw samples or normalized samples. If the first item in the array is a Float, the entire array is assumed to be normalized. Normalized samples are automatically converted into raw samples when saving.

Current Limitations

The mono limitation is by far the biggest. I’m not sure how likely you are to encounter the other limitations.

References

Descriptions of the Wave file format: