Writing .raw audio

I have a simple noise generator that I’d like to output to .raw audio
format using ruby. The bitrate, arbitrarily chosen, is 48,000 and the
samples are 16 bit signed integers. But I am having trouble coming up
with the correct output to write to file. Here is the simplified
program:

samples = Array.new

(0..48000).each { |i| samples[i]=rand(-0x8000..0x7FFF) }

and then I am a little lost. I want to do something like this…

File.binwrite("noise_test.raw", samples)

But that just outputs a big, long array as a series of base 10 integers
separated by commas and spaces. What I need is output in the form of “16
bit signed integers” in a raw binary file. I suppose that would look
like a big long series of zeroes and ones.

I figured it out in case anyone is wondering the same thing.

There is a method that acts on arrays called “pack” that can take the
data in an array and pack it into a dizzying variety of digital formats,
signed, unsigned, 8 bit, 16 bit, 32, 64, big-endian, little endian,
native, and so on and so forth. It’s really comprehensive. You can read
about it at ruby
doc’s page for arrays and the method pack. In my case, the proper
command is:

File.binwrite("noise_test.raw", samples.pack("s<*"))

Thanks to anyone who took a look and either didn’t know what I was
talking about or was befuddled as to whether I had a question or not…
:slight_smile:

Do you happen to have the code available somewhere?

I’d love to learn from it.

I tend to collect snippets into a multimedia project in ruby; just
dumping useful stuff (mostly ffmpeg; aside from ffmpeg I really know
next to nothing about audio).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs