Skip to content

Recording audio#

Relevant example: sound_capture

Recording to a sound buffer#

The most common use for captured audio data is for it to be saved to a sound buffer (SF::SoundBuffer) so that it can either be played or saved to a file.

This can be achieved with the very simple interface of the SF::SoundBufferRecorder class:

# first check if an input audio device is available on the system
if !SF::SoundBufferRecorder.available?
  # error: audio capture is not available on this system

# create the recorder
recorder =

# start the capture

# wait...

# stop the capture

# retrieve the buffer that contains the captured audio data
buffer = recorder.buffer

The SoundBufferRecorder.available? class method checks if audio recording is supported by the system. It if returns false, you won't be able to use the SF::SoundBufferRecorder class at all.

The start and stop methods are self-explanatory. The capture runs in its own thread, which means that you can do whatever you want between start and stop. After the end of the capture, the recorded audio data is available in a sound buffer that you can get with the buffer method.

With the recorded data, you can then:

  • Save it to a file
  • Play it directly
sound =
  • Access the raw audio data and analyze it, transform it, etc.
samples = buffer.samples
count = buffer.sample_count
do_something(samples, count)

If you want to use the captured audio data after the recorder is destroyed or restarted, don't forget to make a copy of the buffer.

Selecting the input device#

If you have multiple sound input devices connected to your computer (for example a microphone, a sound interface (external soundcard) or a webcam microphone) you can specify the device that is used for recording. A sound input device is identified by its name. An Array(String) containing the names of all connected devices is available through the class method SoundBufferRecorder.available_devices. You can then select a device from the list for recording, by passing the chosen device name to the device= method. It is even possible to change the device on the fly (i.e. while recording).

The name of the currently used device can be obtained by calling device. If you don't choose a device yourself, the default device will be used. Its name can be obtained through the default_device class method.

Here is a small example of how to set the input device:

# get the available sound input device names
available_devices = SF::SoundRecorder.available_devices

# choose a device
input_device = available_devices[0]

# create the recorder
recorder =

# set the device
unless recorder.device = input_device
    # error: device selection failed

# use recorder as usual