Skip to content

Microphone

Romain Milbert edited this page Nov 24, 2024 · 5 revisions

To capture audio, a Microphone object needs to be declared. It must take several parameters:

#include <RaZ/Audio/Microphone.hpp>

// ...

// The parameters are:
// - Format; mono & stereo are supported, in 8 & 16 bits
// - Frequency, in Hertz
// - Minimum duration to record, in seconds. The internal buffer may be bigger
// - Optional device name to open; if unspecified or empty, will open the default one
Raz::Microphone mic(Raz::AudioFormat::MONO_U8, 16000, 1.f, {});

⚠️ It should be noted that a stereo mode can be used even with a mono-only capable microphone. You however probably should not do this, as it increases the amount of samples that are captured, for no actual gain since the left & right samples will be duplicated. Use a stereo format only if your application actually requires it.

You can then start capturing audio:

mic.start();

At any point, even during capture, you can check how many samples have been captured and are able to be recovered:

// The number of samples can be fetched
int sampleCount = mic.recoverAvailableSampleCount();

// Alternatively, the available duration can be recovered
float duration = mic.recoverAvailableDuration();

// Note that a sample already takes the format into account. With a frequency of 16000,
//   one second will be equal to 16000 samples, whether in mono/stereo or 8/16 bits

In order to actually recover the captured data, you can do so with a simple function call:

// The following function can take an optional duration argument, which represents the maximum duration
//   (in seconds) to be recovered. It is an upper bound: if less samples are available than needed
//   to last for the given duration, the returned data will be smaller than expected. This can be
//   useful if a specific duration is needed
// If no argument is specified (or if given a negative duration), all available samples will be recovered
std::vector<uint8_t> data = mic.recoverData(1.f);

// Optionally, a Sound object can be fetched, which will contain the captured samples
// This function takes the same duration argument as above
Sound sound = mic.recoverSound(1.f);

To stop recording, simply stop the capture:

mic.stop();

Opening a specific device

Any available audio capture device on your computer can be used. Those can be fetched by calling Raz::Microphone::recoverDevices(). One of the recovered names can then be given at the Microphone's creation, or later as an argument to its openDevice() member function.

Clone this wiki locally