Stitching WAV files together using the wavefile gem

require 'espeak'
require 'wavefile'
include WaveFile

def tts_to_wav(s, wav_file)

  mp3_file = wav_file.sub(/\.wav$/,'.mp3')
  ESpeak::Speech.new(s, voice:  "en-uk-north").save mp3_file

  `mpg123 -w #{wav_file} #{mp3_file}`

end

def append_wavs(wav_files, target_wav)

  Writer.new(target_wav, Format.new(:stereo, :pcm_16, 22050)) do |writer|

    wav_files.each do |file_name|

      Reader.new(file_name).each_buffer(samples_per_buffer=4096) do |buffer|
        writer.write(buffer)
      end

    end
  end

end

tts_to_wav "Test 1.", 'file1.wav'
tts_to_wav "Test 2.", 'file2.wav'
tts_to_wav "Test 3.", 'file3.wav'

append_wavs(%w(file1.wav file2.wav file3.wav), 'file123.wav')

The above example uses the wavefile gem to append 3 wave files (file1.wav + file2.wav + file3.wav) together into 1 wave file (file123.wav).

Resources