# Rendering an mp3 as a waveform image in ruby?

**URL:** <https://www.ruby-forum.com/t/rendering-an-mp3-as-a-waveform-image-in-ruby/144014>\
**Category:** Ruby\
**Created:** [July 24, 2008, 5:35pm UTC](https://www.ruby-forum.com/t/rendering-an-mp3-as-a-waveform-image-in-ruby/144014 "2008-07-24T17:35:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [July 24, 2008, 5:35pm UTC](https://www.ruby-forum.com/t/rendering-an-mp3-as-a-waveform-image-in-ruby/144014/1 "2008-07-24T17:35:26Z")

</div>

Does anyone know of a way, in ruby, to render an mp3 into a waveform  
graphic? Like you’d see in audio editing tools like Audacity,  
Soundforge etc. Just a jpeg as the end result is fine. Hoping there  
might be a gem out there for this…

thanks  
max

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [July 24, 2008, 8:34pm UTC](https://www.ruby-forum.com/t/rendering-an-mp3-as-a-waveform-image-in-ruby/144014/2 "2008-07-24T20:34:45Z")

</div>

2008/7/24 Max W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> Does anyone know of a way, in ruby, to render an mp3 into a waveform  
> graphic? Like you’d see in audio editing tools like Audacity,  
> Soundforge etc. Just a jpeg as the end result is fine. Hoping there  
> might be a gem out there for this…

I don’t think there’s a Ruby gem to allow direct decoding of mp3  
files, however it should be doable using mpg123 or some other program  
callable from the shell which can decode mp3’s.

The command ‘mpg123 -O file.raw file.mp3’ produces raw 16bit stereo  
PCM data (I think sampled at 22KHz) from the .mp3 file and stores it  
in the .raw file. So for every 4 bytes you read the first two bytes  
would be the signal strength of the one channel and the second two  
bytes would be the signal strength of the second channel. You could  
then use String#unpack (I think ‘ss’ will unpack to shorts, which were  
signed 16bits last I checked) to decode these bytes and get the values  
you need. You could then plot these values using a gem like RMagick. I  
haven’t executed this code but it could look like:

File.open(‘file.raw’) do |file|  
while !file.eof?  
first\_channel\_data, second\_channel\_data = file.read(4).unpack(‘ss’)  
# Plot data here  
end  
end

Farrel

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [July 25, 2008, 10:40am UTC](https://www.ruby-forum.com/t/rendering-an-mp3-as-a-waveform-image-in-ruby/144014/3 "2008-07-25T10:40:31Z")

</div>

Ah, that’s useful, thanks farrel.
