Chromed Shark

My various ramblings about programming

Revival of Ruby/audio

I needed to do some audio concatenation for a project I’m working on, and after much research, came to the conclusion that libsndfile would be the easiest to work with. However, with all of the overhead of calling out to a command-line program for every file I wanted to join, I figured it would be better to write a C-based gem wrapper around it. Thus, ruby/audio.

Google quickly led me to Hans’ ruby-audio, which hadn’t had any major modifications since November of 2006. Looking at the forks lead to the most recent fixes by others. After finding and fixing a bug noticed in my audio concatenation project, I decided to turn it into a gem and put it up on Gemcutter.

If you’d like to get started using it, first install ruby-audio from gemcutter: gem install ruby-audio --source="http://gemcutter.org"

Afterwards, simply require audio/sndfile and start writing code. Here’s an example that concatenates a list of files and writes the final file to out.wav.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
require 'rubygems'
require 'audio/sndfile'

out_conf = Sndfile::SF_INFO.new
out_conf.format = Sndfile::SF_FORMAT_WAV|Sndfile::SF_FORMAT_PCM_16
out_conf.channels = 1
out_conf.samplerate = 44100
out = Audio::Soundfile.open('out.wav', 'w', out_conf)

['audio1.wav', 'audio2.wav'].each do |file|
  snd = Audio::Soundfile.open(file)
  buf = Audio::Sound.float(1000)
  read = snd.read(buf)
  while read != 0
    out.write(buf)
    read = snd.read(buf)
  end
  snd.close
end

out.close

My code can be found Github at warhammerkid/ruby-audio, and I expect to make a few more modifications to it to clean up the API and improve the documentation over the next couple weeks.